Dilemma with hashCode() - Java

133 Views Asked by At

I have the following code,

Object testA =  new Object();
Object testB = testA;
System.out.println("A:"+testA.hashCode())
System.out.println("B:"+testB.hashCode())

Per the above, I get the same hashcode for the two objects. I understand that testB is assigned testA and so it could have the same hashcode, however there should be a way to uniquely identify the difference in both these objects right?

Please let me know if there is something obvious that am missing!

3

There are 3 best solutions below

0
On

however there should be a way to uniquely identify the difference in both these objects right?

There is no difference, since there are no two objects. There is just one object referred by two variables.

In theory, two different objects may have the same hashCode. You can tell them apart by using equals or by using ==. If you don't override equals, it behaves as == by default.

3
On

The hashCode function has to be compatible with the equals method in the sense that hashCode has to return the same value for 2 objects that are equal. In this case, they are not only "equal" (according to the equals method), but even the same object (which implies that they are equal).

Besides, independently of what the specification demands, it would impossible for the 2 calls to hashCode to return different values because both variables are actually referencing the same object. There is no way to distinguish testA and testB (apart from the variable name, of course).

0
On

You create a new object testA but then assign testB to testA, which assigns the same memory space for both of the objects. This is why its returning the same HashCode.