Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals() and hashCode()

 
Raef Kandeel
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't get why two objects which returns true for the equals() method must have the same hashCode. Can anybody elaborate?
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consult Effective Java by J Bloch. Best source
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15485
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simple answer is: Because that is what the specification of these methods prescribe (see the API documentation for the two methods in class Object).

Some of the collection classes, especially sets and maps, need this to function properly.
 
Pradeep Meruva
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
logic is very simple, equal() method says two objects are meaningfully equal or not, if two objects are equal their hashcode should also be equal.

some collection classes like HashMap, Hashset etc use this Hashcode() method, while storing the objects. That is the reason specs reccodend to override hashcode() and equal() method while your are using any of the above collections.
 
Pradeep Meruva
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
logic is very simple, equal() method says two objects are meaningfully equal or not, if two objects are equal their hashcode should also be equal.

some collection classes like HashMap, Hashset etc use this Hashcode() method, while storing the objects. That is the reason specs recommend to override hashcode() and equal() method while your are using any of the above collections.
 
Chris Stann
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They don't HAVE to be equal unless you want them to work in collections.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See this post. It contains a link and an explanation that I think will help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic