Why does it not reach the print line “here”? In other words, why is it not using my overridden equals?
Thanks in advance
import java.util.*;
class NumberClass extends Object{
private int number;
public NumberClass(int n){
number=n;
}
@Override
public boolean equals(Object other){
System.out.println("here");
return false;
}
@Override
public String toString(){
return number+"";
}
}
public class HelloWorld {
public static void main(String[] args) {
Set <NumberClass> set= new HashSet<NumberClass>();
set.add(new NumberClass(0));
set.add(new NumberClass(0));
System.out.println(set);
}
}
This is because
HashSetuses the hash code to test whether an object is already in the set and only usesequalsif there is a collision. The default hash code for objects is an internal id, so just because the two objects are equal doesn’t mean they have the same hash code. In this case, there clearly wasn’t a collision, so there was no need for theHashSetto callequals.This is why you should always override
hashCodewhen you overrideequals. See this article for more info on this topic. You should write ahashCodemethod that returns equal hash values for objects that areequals. For instance:The general requirement for
hashCodeis that objects that satisfyequals()should return the same hash code. Note that there’s no requirement that objects that fail anequals()test have different hash codes. If you return a constant (like Jayamohan suggests), that satisfies thehashCodecontract; however, this will completely eliminate the benefits of using aHashSetand you might as well go with a simpleArrayList.