HashSet contains method, strange behavior [duplicate]
here is my code :
public class testGui {
public static void main(String[] arg){
class TESTS{
String t;
public TESTS(String t){
this.t = t;
}
@Override
public boolean equals(Object x){
System.out.println("My method is called...");
if(x instanceof TESTS){
TESTS zzz = (TESTS) x;
return zzz.t.compareTo(t)==0;
}
else return false;
}
}
HashSet<TESTS> allItems = new HashSet<TESTS>();
allItems.add(new TESTS("a"));
allItems.add(new TESTS("a"));
System.out.println(allItems.contains(new TESTS("a")));
}
}
I do not get why the hashset contains method is not calling my equals method as mentionned in their specifications :
More formally, adds the specified element, o, to this set if this set contains no element e such that (o==null ? e=开发者_JAVA技巧=null : o.equals(e))
My code is returning false and not going into my equals method.
Thanks a lot for answering!
When you override equals
, you must also override hashCode
. Otherwise, equal objects will have different hash codes and be considered unequal.
It is also strongly recommended not to override only hashCode
. But this is not essential, as unequal objects can have the same hash code.
The HashSet depends on the HashCode of each object. Before the equals method is called, the hashCode method will be called. If hashcodes are equal, then the hashset deems it worthy of evaluating the equals method.
Implement a hashcode method such that if a.equals(b) == true, then a.hashCode() == b.hashCode()
and it should start working as you would expect.
You should also implement hashCode
, so that it is consistent with equals
. HashSet
uses the hashCode
method to decide which bucket to put an item into, and calls equals
only when the hash code of two items are the same.
Effective Java, 2nd Edition discusses this rule (and the consequences of breaking it) in Item 9: Always override hashCode
when you override equals
.
As most of the comments have been... just override the hashcode method (sample below) and you should be good.
@Override
public int hashCode() {
return t.hashCode()*31;
}
精彩评论