Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java
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
Edited 26-Dec-12 14:01pm
v2
Comments
Sergey Alexandrovich Kryukov at 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

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

Solution 1

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. Smile | :)
 
—SA
  Permalink  
v2

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



Advertise | Privacy | Mobile
Web03 | 2.8.141022.1 | Last Updated 26 Dec 2012
Copyright © CodeProject, 1999-2014
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