File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

diffrence between hashcode and equals method

 
Geetu Kumari
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks !
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic