wood burning stoves 2.0*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hascode and equals" Watch "hascode and equals" New topic
Author

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?


SCJP 6
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: 230
See general contracts:

HashCode

Equals

Also see my post: Overriding hashcode



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

Joined: Sep 28, 2004
Posts: 18532
    
  40

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.

Henry


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

Joined: Sep 28, 2008
Posts: 324
Akash..in 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 Set...so 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)..it 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..]
 
 
subject: hascode and equals
 
Similar Threads
what is hashcode and equals contract?
Hibernate supports equals and not equals
about if-else
confusion between == & equals( )
a question waiting to be cleared