class A{
@Override
public int hashCode() {
return 10;
}
}
public class SampleClass {
public static void main(String[] args){
Map map = new HashMap();
map.put(new A(), "A");
map.put(new A(), "B");
System.out.println(map.size());
System.out.println(new A().hashCode());
System.out.println(new A().hashCode());
}
}
Output :-
2
10
10
Why 2???. If we are implementing hashCode method which is returning same integer. Should not the size be 1???
You haven’t overriden
equals(Object), so they don’t compare as equal.Just because two objects have the same hash code doesn’t mean
HashMapassumes they’re the same — indeed, if that was the case, that would be really, really bad.If you want two
Aobjects to be treated as equal byHashMap, you must overrideequals(Object)inAto define oneAas equal to another.