• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== returning false even when hashcodes are same

 
sridhar t patil
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
Eclipse IDE Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
sridhar t patil
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Debal.

Tried the other way and it is working. It is actaully about operator precedence.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sridhar and Debal. Welcome to the Ranch, both of you!
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ritchie. That was really helpfull.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic