File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashcode - What is it for?

 
Joe Richard
Ranch Hand
Posts: 76
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is so important about a hashcode?

I have not found a time when I need to have one.
:roll:
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The hashCode() method provides a semi-unique identifier for an object, useful in various sorting and searching algorithms. If you've used the Hashtable or HashMap classes, then you've relied on your key objects having sensible hashCode() methods.
 
Jeff Storey
Ranch Hand
Posts: 230
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To follow up on that, two objects that are equals must also have the same hashcode. As Ernest pointed out, the hash codes can be used in HashMaps and HashSets. What happens is that if you tell a HashSet to look for an object, it hashes the object you tell it to look for and then finds if it has an object with the same hashcode. Then it checks if they are equals. This way it doesn't have to check equals (which could be expensive) on every object in the set.

As I stated above, two equals objects must have the same hashcode, but just because two objects have the same hashcode does not mean they are equal. A good hashcode function distributes objects evenly across different hash "buckets." Do some searching on Google and I'm sure you will find more information.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic