aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals( ) & hashCode( ) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals( ) & hashCode( )" Watch "equals( ) & hashCode( )" New topic
Author

equals( ) & hashCode( )

ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
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

Joined: Dec 29, 2004
Posts: 1071
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

Joined: Oct 11, 2004
Posts: 3830
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

Joined: Dec 29, 2004
Posts: 1071
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

Joined: Aug 27, 2004
Posts: 411
Steven,
I tested that. You are correct


Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
Thanks everybody .
Actually I never paid attention on their radix ... otherwise I never post here ...
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

See this post (again)...

http://www.coderanch.com/t/398243/java/java/hash-codes
[ January 25, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals( ) & hashCode( )