It's not a secret anymore!*
The moose likes Java in General and the fly likes == returning false even when hashcodes are same Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "== returning false even when hashcodes are same" Watch "== returning false even when hashcodes are same" New topic
Author

== returning false even when hashcodes are same

sridhar t patil
Greenhorn

Joined: May 05, 2011
Posts: 6
I wrote a following code snippet to see how == works.



This is printing false and even the hashcodes of a1 and a2 are same. Please help me understand this behavior.
Debal Guha
Greenhorn

Joined: Feb 21, 2013
Posts: 9

The print statement you have written is actually interpreted like this


You could have get the desired output if you have written like this


This will return true.


You just need to know where to find it!!
sridhar t patil
Greenhorn

Joined: May 05, 2011
Posts: 6
Thanks Debal.

Tried the other way and it is working. It is actaully about operator precedence.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

Hi Sridhar and Debal. Welcome to the Ranch, both of you!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38100
    
  22
Welcome to the Ranch both of you. Nice catch about the precedences.
You cannot expect == to return true when you have the same hashCodes. The hash code does not give you the memory location of the object. And objects which have different memory locations but return true from equals() must return the same hash code.
Try this:-You should get false true.
Try this, too.
sridhar t patil
Greenhorn

Joined: May 05, 2011
Posts: 6
Thanks Ritchie. That was really helpfull.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: == returning false even when hashcodes are same
 
Similar Threads
exam lab gc question
How many Objects are elligible for Gabbage Collection at Line 17?
Array Qn
Garbage collection
Garbage Collection (Cyclic references) Also known as Object Island