HashSet contains method, strange behavior

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 understand why hashset contains a method that does not call my equals method, as indicated in their specifications:

More formally adds the indicated element, o, to this set if this set does not contain an element e such that (o == null? E == null: o.equals (e))

My code returns false and is not part of my equals method.

Thank you very much for your answer!

+6
java
source share
4 answers

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 that you do not override only hashCode . But this is not essential, since unequal objects can have the same hash code.

+13
source share

HashSet depends on the HashCode of each object. Before calling the equals method, the hashCode method is called. If the hash codes are equal, then the hashset considers this worthy of the evaluation of the equals method.

Implement the hashcode method, so if a.equals (b) == true, then a.hashCode () == b.hashCode ()

and it should start working as you expected.

+7
source share

You must also implement hashCode so that it matches equals . HashSet uses the hashCode method to determine which forging the item is placed in, and calls equals only when the hash code of the two items is the same.

Effective Java, 2nd Edition discusses this rule (and the consequences of breaking it) in Clause 9: Always override hashCode when overriding equals .

+3
source share

Since most of the comments were ... just override the hashcode method (sample below) and you should be good.

 @Override public int hashCode() { return t.hashCode()*31; } 
0
source share

All Articles