If two objects have same hashcode value,they are not required to be equal,but if they are equal they must have same hashCode
OCPJP - 93%
Arun Giridharan wrote:
If two objects have same hashcode value,they are not required to be equal,but if they are equal they must have same hashCode
I'm not understanding the above line.![]()
![]()
bhanu chowdary wrote:Suppose if I have a hash algorithm which calculates a hash like this
A B C D E ...... Z
1 2 3 4 5 ...... 26
so for a string "bhanu" my hash will be 2 + 8 + 1 + 14 + 21 = 46
and for the reverse string "unahb" the value is 21 + 14 + 1 + 8 + 2 = 46
In the above case both strings are not the same but the hash value returned is the same. Therefore two objects are not necessarily be equal if the hashcode is same. To determine the equality you have to check for the content of both the strings.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
Arun Giridharan wrote:does this means we shouldn't override hashCode() method without overriding equal() method ,right ?
but the real equal() method in Object class only calls hashCode() method to verify objects are equal or not, that doesn't prove the contract , right ?
Arun Giridharan wrote:but still i didn't understand why i need to override hashCode() when i need to override equal() method ? (or viceversa
Dennis Deems wrote:
NO! equals does NOT call hashCode!
The implementation of equals in the Object class is this:
Matthew Brown wrote:No. Dennis has shown you the code for equals() in the Object class - you can check it yourself if you don't believe him.
Arun Giridharan wrote:
Matthew Brown wrote:No. Dennis has shown you the code for equals() in the Object class - you can check it yourself if you don't believe him.
Isn't that this refer to an address if(this==obj) means it's comparing the address , the address(int value) must be received from hashCode() , internally it must access the hashCode() !!![]()
Dennis Deems wrote:Ah, now I see your confusion. No, the memory address and the hash code are two entirely different things.
Consider Paul's rocket mass heater. |