Click here to Skip to main content
13,455,913 members (48,802 online)
Rate this:
Please Sign up or sign in to 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 26-Dec-12 13:59pm
Updated 26-Dec-12 14:01pm
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.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Hash code is not in Java. This is important algorithm use everywhere in computing:[^].

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.


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. :-)


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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03-2016 | 2.8.180322.1 | Last Updated 26 Dec 2012
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100