This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hascode and equals 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 "hascode and equals" Watch "hascode and equals" New topic

hascode and equals

akash azal
Ranch Hand

Joined: Jan 31, 2009
Posts: 70
why if two objects are equals their hashcode must be equal??

We will keep things moving!!
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
akash azal wrote:why if two objects are equals their hashcode must be equal??

Did you read hashing and bucket mechanism in chapter 7 of K&B?
Do you know where hashCode() and equals() are used?

akash azal
Ranch Hand

Joined: Jan 31, 2009
Posts: 70
i read k&b chapter 7 .
euals() method is used to check objects are meaningfully equivalent or not.
but my doubt is y reverse is not true
Jari Timonen
Ranch Hand

Joined: Jan 16, 2004
Posts: 232
See general contracts:



Also see my post: Overriding hashcode

SCJP 5.0, SCJD URLyBird 1.3.3, OCMJEA 5 (SCEA) Factory Homes
Henry Wong

Joined: Sep 28, 2004
Posts: 20038

Hashing is more of an algorithm than the Java implementation. So if you want to know "why" something is, it may be better to pick up a book on algorithms, than look at the JavaDocs... All the JavaDocs will do is give you the contracts, not the explanations.

but my doubt is y reverse is not true

Reverse of what is not true? Please clarify the question.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Himalay Majumdar
Ranch Hand

Joined: Sep 28, 2008
Posts: 324 collections..let say in Sets. Duplicates are not allowed. For better performance, set first uses hashcode to determine if a similar object is already in the Set.
If hashcode differs it will directly put it inside the even if objects are meaningfully equal its putting them..and creating a duplicate element.

But the reverse is not true i.e two different objects can have the same hashcode. If a Set gets the same hashcode(hashcode is just the bucket-id) wont directly discard the object as duplicate. It will go to the appropriate bucket depending on hashcode and compare the objects using equals() method.

If you practice with them for a while..u will surely get it.

SCJP 1.6, SCWCD 5.0, SCBCD 5.0 [loading..]
I agree. Here's the link:
subject: hascode and equals
It's not a secret anymore!