| Author |
equals() and hashCode()
|
Harikrishna Gorrepati
Ranch Hand
Joined: Sep 23, 2010
Posts: 422
|
|
|
Hi, Why do I hear this sentence quite often "When you override equals() method, override hashCode() method also". From the following code, without hashCode() method, I am able to compare and print true. Also, I am thinking that hashCode() is useful only if we use either HashSet or HashMap. Am I correct/ wrong? Please advice
|
OCPJP 6.0-81% | Preparing for OCWCD
http://www.certpal.com/blogs/cert-articles | http://sites.google.com/site/mostlyjava/scwcd |
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14669
|
|
This answer is in the API of the Object#equals method :
API wrote:
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
|
[My Blog]
All roads lead to JavaRanch
|
 |
Himanshu Gupta
Greenhorn
Joined: Nov 21, 2007
Posts: 4
|
|
It is good to follow the contract because there may be other guys in the team who wants to put the Objects in the Hash Collections<HashMap, HashSet>.
This can result in giving some unusual behavior and unexpected results.
|
 |
Rikesh Desai
Ranch Hand
Joined: Jun 02, 2010
Posts: 83
|
|
Oh ok.
So does this mean, (as Harikrishna pointed out), that we need to use HashCode implementation just for HashSet, HashTable and HashMap?
Wont we need to implement it for TreeMap too?
|
OCPJP 95%
|
 |
Harikrishna Gorrepati
Ranch Hand
Joined: Sep 23, 2010
Posts: 422
|
|
Rikesh Desai wrote:Oh ok.
So does this mean, (as Harikrishna pointed out), that we need to use HashCode implementation just for HashSet, HashTable and HashMap?
Wont we need to implement it for TreeMap too?
Hi Rikesh, Christophe and Himanshu are saying something like this. Add this code to the program.
Do you see, we are getting 2 different outputs (may differ in your system), which it should NOT be as per contract. We need to implement hashCode() wherever you write equals() method. That's why String and wrapper classes implements these 2 methods.
|
 |
Trivikram Kamat
Ranch Hand
Joined: Sep 26, 2010
Posts: 155
|
|
Harikrishna Gorrepati wrote:
I am thinking that hashCode() is useful only if we use either HashSet or HashMap.
Rikesh Desai wrote:
So does this mean, (as Harikrishna pointed out), that we need to use HashCode implementation just for HashSet, HashTable and HashMap?
hashCode() is method in java.lang.Object
As all classes inherit java.lang.Object, hanshCode() is also inherited.
It can be used in any class, only thing is that equals() should maintain general contract with hashCode() as told by Christophe Verré
|
OCPJP6
|
 |
 |
|
|
subject: equals() and hashCode()
|
|
|