aspose file tools*
The moose likes Beginning Java and the fly likes diffrence between hashcode and equals method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "diffrence between hashcode and equals method " Watch "diffrence between hashcode and equals method " New topic
Author

diffrence between hashcode and equals method

Geetu Kumari
Greenhorn

Joined: Mar 10, 2008
Posts: 5
Hi,

Can anybody explain me the difference between hashCode() and equals() methods. I have read it from book but not quiet clear how to use them in programs. If possible please give some example also. How hashCode() comes in picture while working with == and equals() methods.


Thanks in advanced.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

http://en.wikipedia.org/wiki/Hashcode
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

If two instances have the same value, we expect them to to be equals, but they should also have the same hash value.

A hash value is like a quick-lookup version of the value of the instance. If they are equal then they must have the same hash value, but having the same hash value doesn't necessarily mean they are equal.

HashMaps use this 'quick lookup' property of Objects create fast storage. Provided the Class implementation behaves responsibly, an instance can be found in constant time, regardless of the size of the HashMap. This is pretty impressive considering there may be millions, 10's, 100's of millions or billions of objects in the hashMap.

It does this by looking for the 'hash' value, and then finding whether the retrieved instances is 'equals' as a second step. Using only equals would require looking at every one of the billion items.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
Welcome to JavaRanch

Do a Google search for Joshua Bloch's Effective Java; somewhere on the Sun Java� website there is a sample of this book (chapter 3) and it has equals and hashCode in (at least it used to). Also go through the Object class API documentation where you find the specifications for hashCode and equals.
Geetu Kumari
Greenhorn

Joined: Mar 10, 2008
Posts: 5
Thanks !
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: diffrence between hashcode and equals method