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==null : o.equals(e))
My code is returning false and not going into my equals method.
Thanks a lot for answering!
HashSet. contains() method is used to check whether a specific element is present in the HashSet or not. So basically it is used to check if a Set contains any particular element. Parameters: The parameter element is of the type of HashSet.
HashSets are used to store a collection of unique elements. HashSet cannot contain duplicate values. HashSet allows null value. HashSet is an unordered collection.
The purpose of the contains method is to check if an element is present in a given HashSet. It returns true if the element is found, otherwise false. Whenever an object is passed to this method, the hash value gets calculated. Then, the corresponding bucket location gets resolved and traversed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With