I have a class that contains different enums (different types). This class is used as key for a HashMap. The classes hashCode currently is implemented like this:
public static class Key implements Comparable<Key> {
final int a;
final Enum1 enum1;
final Enum2 enum2;
@Override
public int hashCode() {
return a ^ enum1.hashCode() ^ enum2.hashCode();
}
// ... definition of equals and toString ...
}
Now if enums hashCode would just return the index of the enum value in the enum’s definition, this would not be optimal (too many clashes). The method definition for Enum.hashCode() is this:
/**
* Returns a hash code for this enum constant.
*
* @return a hash code for this enum constant.
*/
public final int hashCode() {
return super.hashCode();
}
Assuming this delegates to Object.hashCode(), everything should be fine because for every enum constant there only exists one instance, and Object.hashCode() will in theory be something like an integer derived from the internal address of the object. Am I right?
PS: Of course you will have to use something more complex when the same enum is used several times in a key.
Yes, you are right in that the hashcode of an enum element will come from the static instance, bound to memory positions, and be unique.
On the other hand, there are better ways of generating a hashcode with less collision probability. Check out, for example, the defaults that eclipse can autogenerate for you (right click, Source> Generate hashCode and equals)
By throwing prime numbers into the mix (the precise math escapes me) you are supposed to be a little more resistant.
Note you can also let eclipse generate an equals method for you! (Even a toString). Not saying you must blindly trust them, but they are usually a very good start.