我有一个包含不同枚举类型的类。这个类被用作 HashMap
的键。该类的哈希码目前实现如下:
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 ...
}
如果枚举的 hashCode 方法只是返回枚举值在枚举定义中的索引,那么这并不是最优的(会导致太多冲突)。Enum.hashCode()
方法的定义如下:
/**
* Returns a hash code for this enum constant.
*
* @return a hash code for this enum constant.
*/
public final int hashCode() {
return super.hashCode();
}
假设这个委托给了 Object.hashCode()
,因为对于每个枚举常量只存在一个实例,在理论上 Object.hashCode()
将会是从对象的内部地址派生出来的整数。我说得对吗?
PS: 当同一个枚举在键中被多次使用时,当然你需要使用更复杂的东西。
myEnum.ordinal()
和myEnum.hashCode()
并比较结果来检查。 - Dunes