• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hascode and equals

 
akash azal
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why if two objects are equals their hashcode must be equal??
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See general contracts:

HashCode

Equals

Also see my post: Overriding hashcode


 
Henry Wong
author
Marshal
Pie
Posts: 21493
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic