• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Equals and HasCode

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Source: MasterExam



The answer given is C, E.
But A, B are also correct?
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, they are not correct Abhi. The way to think about the three relationships (hashCode() values, equals() return, and == return) is:
The most strict (specific) relationship is ==. If == is true, you can be assured that if the implementations of equals and hashCode are correct, equals will return true, and the hashCode values will be the same.
The next relationship in order of strictness is equals. If equals is true, you must have that hashCode values are the same.
Finally, you have hashCode. This is the least strict relationship. Even for completely unrelated objects of the same class, hashCode may return the same values.
Let me know if that makes sense, and try to reason why A and B are false.
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hope Ruben cleared your doubt, Just an example here



For option A: Even though the objects are meaningfully equal, there memory location is not same.
For option B: it says "x==y may be true.". If it is true then it MUST be equal.

Hope i am clear.
 
Balagopal Kannampallil
Ranch Hand
Posts: 136
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"==" refers to the memory where the objects are located. If both the objects lies on the same location "==" will return true.
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That makes perfect sense.
But while adding objects to a hash-based collection we say that if you override the equals() method and dont override the hashCode() then the 2 objects will be considered unequal or different.
So I was trying to figure out the answer that way.
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abhi vijay wrote:That makes perfect sense.
But while adding objects to a hash-based collection we say that if you override the equals() method and dont override the hashCode() then the 2 objects will be considered unequal or different.
So I was trying to figure out the answer that way.


Good, Hash based collections first matches hashCode of both objects , if both objects found in same bucket than only it will call equals(Object) method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic