I am creating 3 objects of same class: A,B,rB. Here rB is referencing to B. And values of A and B are equal. I had overrided equals method where I am comparing the values.
So
A.equals(B), A.equals(rB) and B.equals(rB) is true. But A != B, A !=
rB and B == rB.
Now I am putting A,B,rB in HashMap, say hm, and IdentityHashMap, say ihm.
hm.put(A, "1");
hm.put(B, "2");
hm.put(rB, "3");
ihm.put(A, "1");
ihm.put(B, "2");
ihm.put(rB, "3");
Since I am not storing null, so hm.get(A) should return 3, hm.get(B) should return 3 and hm.get(rB) should return 3.
Similarly, ihm.get(A) should return 1, ihm.get(B) should return 3 and ihm.get(rB) should return 3.
As per the java docs, IdentityHashMap does k1 == k2 while HashMap does k1.equals(k2) , if k1 and k2 are not null.
So why hm.get(A) is returning 1.
You say that you overrode
equals, but did you overridehashCodeas well? If not, then this is likely to be the cause of the behaviour you are seeing.HashMapwill only useequalswhen two keys have the same hash code, so it is essential that whenever you overrideequalsyou also overridehashCodeand vice versa.