How to implement hashCode? You should implement „hashCode“ so that EQUAL objects return the same hashCode. Therefore I should take the objects instance variable which is compared for equality in equals method and call the hashCode() to return an int number which is the same for equal objects. In this example I calculate the hashCode from the string instance variable which is turning the balance for equality of two objects. My Question is: - Is this implementation ok? - I assume „empNum.hashCode( )“ is neccessary to convert a string in an int which is then returned as „int hashCode() must return an int value. Would it be neccessary to say „empNum.hashCode( )“ if „empNum“ would already be an int instead of a String? - How would I calculate a hashCode if equals() method would compare two instance variables „empNum“ and „name“ instead of one?
Originally posted by Thomas Markl: - Is this implementation ok?
Would it be neccessary to say „empNum.hashCode( )“ if „empNum“ would already be an int instead of a String?
No, it would not be necessary.
- How would I calculate a hashCode if equals() method would compare two instance variables „empNum“ and „name“ instead of one?
You would somehow combine them to get a single int value. A simple solution would be "empNum + name.hashCode()".
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
If empNum is an int, you can't say empNum.hashCode(). You can only call hashCode() on objects, not primitives.
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Joined: Mar 08, 2001
Hello Ilja and Ron, I am not quite clear about how to override the hashCode() method if „equals()“ compares two instance variables. Therefore I gave it a try in the code above and overrode hashCode() this way:
You can see that equals compares two instance variables and hence hashCode() combines the two instance Varialbes and retrieves an int from the combined strings by using hashCode(). Did I override hashCode correctly in the code above. I checked the overridden hashCode() in the sample code (see below) and I think it Works because it returns the same hashCode for equal objects e1 and e3.