wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals() and hashCode() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals() and hashCode()" Watch "equals() and hashCode()" New topic
Author

equals() and hashCode()

Raef Kandeel
Ranch Hand

Joined: Aug 05, 2007
Posts: 87
I don't get why two objects which returns true for the equals() method must have the same hashCode. Can anybody elaborate?


SCJP, SCWCD
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
Consult Effective Java by J Bloch. Best source
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Pradeep Meruva
Greenhorn

Joined: Aug 13, 2007
Posts: 7
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,<br />SCJP.
Pradeep Meruva
Greenhorn

Joined: Aug 13, 2007
Posts: 7
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

Joined: Oct 10, 2006
Posts: 49
They don't HAVE to be equal unless you want them to work in collections.


EXCEL IN ALL YOU DO
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

See this post. It contains a link and an explanation that I think will help.


"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() and hashCode()
 
Similar Threads
what is hashcode and equals contract?
HashSet ordering
map method containsKey
equals - hashcode
On Sets