在HashMap中了解equals和hashCode的工作原理 [英] Understanding the workings of equals and hashCode in a HashMap
问题描述
我有这个测试代码:
import java.util。*;
$ b $ class MapEQ {
public static void main(String [] args){
Map< ToDos,String> m = new HashMap< ToDos,String>();
ToDos t1 =新的ToDos(星期一);
ToDos t2 =新的ToDos(星期一);
ToDos t3 =新的ToDos(星期二);
m.put(t1,doLaundry);
m.put(t2,payBills);
m.put(t3,cleanAttic);
System.out.println(m.size());
}}
类ToDos {
字符串日;
ToDos(String d){day = d; }
public boolean equals(Object o){
return((ToDos)o).day == this.day;
}
// public int hashCode(){return 9; }
当 // public int hashCode(){返回9; }
被取消注释 m.size()
返回2,当它留下评论时返回3。为什么?
如果没有重写<$ c $,你已经得到了等于
C>的hashCode 。您必须确保对于两个对象等于
返回true的所有情况, hashCode
返回相同的值。哈希码是一个代码,如果两个对象相等,则该代码必须相等(反之不必为真)。当你把你的硬编码值设为9时,你再次满足合同。
在你的哈希映射中,等式只在一个哈希桶中被测试。你的两个星期一对象应该是相等的,但是因为它们返回不同的哈希码,所以等于
方法甚至没有被调用来确定它们的相等性 - 它们被直接放入不同的桶中,甚至没有考虑到它们相同的可能性。
I have this test code:
import java.util.*;
class MapEQ {
public static void main(String[] args) {
Map<ToDos, String> m = new HashMap<ToDos, String>();
ToDos t1 = new ToDos("Monday");
ToDos t2 = new ToDos("Monday");
ToDos t3 = new ToDos("Tuesday");
m.put(t1, "doLaundry");
m.put(t2, "payBills");
m.put(t3, "cleanAttic");
System.out.println(m.size());
} }
class ToDos{
String day;
ToDos(String d) { day = d; }
public boolean equals(Object o) {
return ((ToDos)o).day == this.day;
}
// public int hashCode() { return 9; }
}
When // public int hashCode() { return 9; }
is uncommented m.size()
returns 2, when it's left commented it returns three. Why?
You have overidden equals
without overriding hashCode
. You must ensure that for all cases where equals
returns true for two objects, hashCode
returns the same value. The hash code is a code that must be equal if two objects are equal (the converse need not be true). When you put your hard-coded value of 9 in, you satisfy the contract again.
In your hash map, equality is only tested within a hash bucket. Your two Monday objects should be equal, but because they are returning different hash codes, the equals
method isn't even called to determine their equality - they are put straight into different buckets, and the possibility that they are equal isn't even considered.
这篇关于在HashMap中了解equals和hashCode的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!