aspose file tools*
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
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: 4465
    
    8

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

Joined: Oct 13, 2005
Posts: 39834
    
  28
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.
 
Consider Paul's rocket mass heater.
 
subject: == returning false even when hashcodes are same