• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals( ) & hashCode( )

 
ankur rathi
Ranch Hand
Posts: 3830
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is one statement is 7th chapter of K&B :
If you don't override the equals() method , you will not be able to use the object as a key in a hashtable .

Can any body explain me this line . I am not getting from the book .
One more thing is what is the connection b/w this two method .
thank you vary much .
 
Steven Bell
Ranch Hand
Posts: 1071
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are going to use an Object as a key in a hashtable you need to override both equals and hashcode.

If you don't override hashcode the hashtable will not be able to find the key unless you keep that object around (which defeats the purpose of haveing a hashtable) because the hashtable will look for the key by hashing the hashcode first. Once it finds the right key location there can be several Object keys in that location so it compares the Objects with the equals method. If they are not equals() it will not find it. If you don't override equals() then equals() just tests ==. (I hope that made sense)

Anytime you override equals() you should always override hashcode and visaversa.
 
ankur rathi
Ranch Hand
Posts: 3830
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is mentioned in K&B that : If we pass an object reference in SOP then it prints the class name + @ + hash code .
But look at this code :


why this two hash codes are different for the same object .

please help .
thanks .

For first question can any body put some code . thanks .
 
Steven Bell
Ranch Hand
Posts: 1071
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't test this, but I think they are the same number, just one is in binary and one is in hex.
 
Jay Pawar
Ranch Hand
Posts: 411
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steven,
I tested that. You are correct
 
ankur rathi
Ranch Hand
Posts: 3830
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everybody .
Actually I never paid attention on their radix ... otherwise I never post here ...
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See this post (again)...

http://www.coderanch.com/t/398243/java/java/hash-codes
[ January 25, 2005: Message edited by: marc weber ]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic