The answer given is C, E.
But A, B are also correct?
Ruben Soto
Ranch Hand
Joined: Dec 16, 2008
Posts: 1032
posted
0
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.
All code in my posts, unless a source is explicitly mentioned, is my own.
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.
SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
"==" refers to the memory where the objects are located. If both the objects lies on the same location "==" will return true.
Bala
SCJP 5.0
Gonna hunt down SCWCD soon..
Abhi vijay
Ranch Hand
Joined: Sep 16, 2008
Posts: 509
posted
0
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
Joined: Oct 16, 2008
Posts: 952
posted
0
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.