This is the java main()
method:
public static void main(String[] args) {
HashSet<Mapper> set = new HashSet<Mapper>();
Mapper test = new Mapper("asd", 0);
set.add(test);
System.out.println(new Mapper("asd", 0).equals(test));
System.out.println(set.contains(new Mapper("asd", 0)));
}
My Mapper
class is:
class Mapper {
String word;
Integer counter;
Mapper (String word, Integer counter) {
this.word = word;
this.counter = counter;
}
public boolean equals(Object o) {
if ((o instanceof Mapper) && (((Mapper)o).word == this.word)) {
return true;
}
return false;
}
}
and the result is :
true
false
From HashSet specifications, at this method I read this:
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
Can anyone explain me where I'm wrong?
You need to implement a proper hashCode()
function.
public int hashCode() {
// equal items should return the same hashcode
}
The Java utilites java.util
contain a lot of classes which rely on hashing. To allow one to override equals()
as they see fit means that one must also properly override hashCode()
to match.
A correct implementation of hashCode()
would return the same hash for any two objects where equals()
returns true. Hash related functions check the hashes for equality before checking to see if the objects equal (to resolve hash collisions).