Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
After reading several articles and official documents, I could not get the actual purpose of having hashcode in Java.

Somewhere it was mentioned that it is a contract for object comparison using the equals() method. Two objects which are same must have the same hashcode but two unequal objects don't necessarily have different hashcode in each. It's really confusing.

Could you please explain in plain language the purpose of hashcode in Java? What does it really make a difference, if Java doesn't have hashcode?
Posted
Updated 26-Dec-12 14:01pm
v2
Comments
Sergey Alexandrovich Kryukov 26-Dec-12 20:22pm    
Indeed, this thing is hardly properly explained in original API documentation. However, an elementary course on algorithms should explain it, so all professionals are supposed to know such thing. Anyway, the question makes sense and practically important. I voted 4. And answered.
Cheers,
—SA

1 solution

Hash code is not in Java. This is important algorithm use everywhere in computing:
http://en.wikipedia.org/wiki/Hash_function[^].

In Java, it is important because your class can be uses in some collection based on the algorithms using hash code. Your elements will behave correctly in such algorithms only if you provide some implementation of this function as soon as you define your own equality method. Logically equal objects should manifest equal hash code values, and unequal objects should return values of the hash code which are different with high probability — this is the major requirement for the class implementation.

Sorry, I don't want to explain it once again. Please see my explanation I once provided for .NET:
Object.GetHashCode() Method in C#.Net[^].

In Java, everything is the same, only it has different but similar collection types.

[EDIT]

You might be puzzled to know how should you implement hash code for your classes when it is required. I'll give you a very simple recipe. Consider your class has several fields which are use in equals implementation. Supposing they already have implementation of hash code, take all their hash code values and make a binary XOR of all of them. Return the resulting value as a hash code of the composing object. That's it.

For a home exercise, think why this implementation works. :-)

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900