class Hash {
int a;
Hash(int h){
a=h;
}
public boolean equals(Object o) {
Boolean h=super.equals(o);
System.out.println("Inside equals ");
return h;
}
public int hashCode() {
System.out.println("Inside Hash");
return 2;
}
}
public class Eq {
public static void main(String...r) {
HashMap<Hash,Integer> map=new HashMap<Hash,Integer>();
Hash j=new Hash(2);
map.put(j,1);
map.put(j,2);
System.out.println(map.size());
}
}
output was
inside hash inside hash 1
Since it returns the same hashcode , the second time an object is added in hashmap it must use the equals method but it doesnt call . So wats the problem here?
From the doc
The
HashMap
is testing with==
before.equals
, and since you are putting the same object twice, the first test passes. Try with:The equality check is done by HashMap in three steps:
The second step prevents calling
equals
since identical objects are always assumed equal.