File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes hashcode -  What is it for? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "hashcode -  What is it for?" Watch "hashcode -  What is it for?" New topic

hashcode - What is it for?

Joe Richard
Ranch Hand

Joined: Aug 15, 2001
Posts: 76
What is so important about a hashcode?

I have not found a time when I need to have one.

Persistence equals goals
SCJD (In Progress), SCJP
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
Jeff Storey
Ranch Hand

Joined: Apr 07, 2007
Posts: 230
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:
subject: hashcode - What is it for?
It's not a secret anymore!