Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dilemma with hashCode() - Java

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!

like image 254
Faz Avatar asked Dec 14 '22 13:12

Faz


1 Answers

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.

like image 153
Eran Avatar answered Dec 17 '22 02:12

Eran