Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Warning, don't use Object == Object (in Java)

davidthi808-JavaNetMar 31 2014 — edited Apr 3 2014

In Java the following code can return false:

IntegerPlus o1 = new IntegerPlus(1000);

IntegerPlus o2 = o1;

boolean b1 = o1 == o2;

boolean b2 = o1.equals (o2);

b1 & b2 will usually be true, but can be false. Yes, you are comparing two references to the same object and the equality test can fail. What I think is happening (the companies creating JVMs say virtually nothing about how the JVMs are implemented) is as follows:

o1 & o2 are references to an object. That object can be moved in memory when the garbage collector runs. The == uses System.identityHashCode() to determine if the objects are identical. I believe this is the address of the object in memory at the time the object is created. So o1 is created & identiyHashCode is assigned to it, the object is moved, then it is assigned to a new reference o2 which then makes its own call to identityHashCode and has a different number.

REMOVEDThe bottom line is - don't use == on objects.

Update: I changed Equals() to equals() - sometime auto-capitalization is not your friend.

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 1 2014
Added on Mar 31 2014
17 comments
8,687 views