我们如何决定集合的hashCode()方法的最佳实现(假设equals方法已被正确重写)?
当前回答
由于您特别要求集合,我想添加一个其他答案还没有提到的方面:HashMap不期望它们的键在添加到集合后改变它们的hashcode。会破坏整个目的…
其他回答
由于您特别要求集合,我想添加一个其他答案还没有提到的方面:HashMap不期望它们的键在添加到集合后改变它们的hashcode。会破坏整个目的…
我在arrays . deephashcode(…)周围使用了一个小包装器,因为它可以正确地处理作为参数提供的数组
public static int hash(final Object... objects) {
return Arrays.deepHashCode(objects);
}
任何在可能的范围内均匀分布哈希值的哈希方法都是一个很好的实现。参见effective java (http://books.google.com.au/books?id=ZZOiqZQIbRMC&dq=effective+java&pg=PP1&ots=UZMZ2siN25&sig=kR0n73DHJOn-D77qGj0wOxAxiZw&hl=en&sa=X&oi=book_result&resnum=1&ct=result),其中有一个关于hashcode实现的好技巧(第9项我认为…)
标准实现很弱,使用它会导致不必要的冲突。想象一个
class ListPair {
List<Integer> first;
List<Integer> second;
ListPair(List<Integer> first, List<Integer> second) {
this.first = first;
this.second = second;
}
public int hashCode() {
return Objects.hashCode(first, second);
}
...
}
Now,
new ListPair(List.of(a), List.of(b, c))
and
new ListPair(List.of(b), List.of(a, c))
List的乘数具有相同的hashCode,即31*(a+b) + c。hashCode在这里被重用。显然,碰撞是不可避免的,但产生不必要的碰撞只是……不必要的。
There's nothing substantially smart about using 31. The multiplier must be odd in order to avoid losing information (any even multiplier loses at least the most significant bit, multiples of four lose two, etc.). Any odd multiplier is usable. Small multipliers may lead to faster computation (the JIT can use shifts and additions), but given that multiplication has latency of only three cycles on modern Intel/AMD, this hardly matters. Small multipliers also leads to more collision for small inputs, which may be a problem sometimes.
使用质数是没有意义的,因为质数在环Z/(2**32)中没有意义。
因此,我建议使用随机选择的大奇数(可以选择质数)。由于i86/amd64 cpu可以使用更短的指令来匹配一个有符号字节的操作数,因此对于像109这样的乘法器来说,速度优势很小。为了最小化冲突,可以使用类似0x58a54cf5的值。
在不同的地方使用不同的乘数是有帮助的,但可能不足以证明额外的工作是合理的。
使用Apache Commons EqualsBuilder和HashCodeBuilder上的反射方法。
推荐文章
- Android Studio无法找到有效的Jvm(与MAC OS相关)
- 为什么一个组合器需要减少方法转换类型在java 8
- CountDownLatch是如何在Java多线程中使用的?
- 如果我同步了同一个类上的两个方法,它们能同时运行吗?
- 如何减去X天从一个日期对象在Java?
- Java标识符中的“连接字符”是什么?
- 如何将新项目添加到哈希
- 一对多、多对一、多对多的区别?
- 从枚举中选择一个随机值?
- 如何从URL获取参数与JSP
- 如何在Eclipse中生成Javadoc注释?
- 找到java类从哪里加载
- 从集合中随机选取一个元素
- 为什么x == (x = y)和(x = y) == x不一样?
- 什么Java 8流。收集等价物可在标准Kotlin库?