集合的hashCode方法的最佳实现 [英] Best implementation for hashCode method for a collection

查看:118
本文介绍了集合的hashCode方法的最佳实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何决定集合的 hashCode()方法的最佳实现(假设已正确覆盖equals方法)?

How do we decide on the best implementation of hashCode() method for a collection (assuming that equals method has been overridden correctly) ?

推荐答案

最佳实施方案?这是一个难题,因为它取决于使用模式。

The best implementation? That is a hard question because it depends on the usage pattern.

对于几乎所有情况,在 Josh Bloch 中提出了合理的良好实施第8项(第二版)中的 有效Java 。最好的方法是在那里查找,因为作者解释了为什么这种方法很好。

A for nearly all cases reasonable good implementation was proposed in Josh Bloch's Effective Java in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is good.


  1. 创建 int结果并指定非零值。

对于每个字段 f 中测试等于()方法,通过以下方式计算哈希码 c

For every field f tested in the equals() method, calculate a hash code c by:


  • 如果字段f是布尔值
    计算(f?0:1);

  • 如果字段f是字节字符 int :计算(int)f ;

  • 如果字段f是 long :calculate (int)(f ^(f>>> 32));

  • 如果字段f是 float :计算 Float.floatToIntBits( f);

  • 如果字段f是 double :计算 Double .doubleToLongBits(f)并像每一个一样处理返回值long值;

  • 如果字段f是对象:使用 hashCode()的结果方法或0如果 f == null ;

  • 如果字段f是数组:请参阅每个字段作为单独的元素,并以递归方式计算哈希值并组合下面描述的值。

  • If the field f is a boolean: calculate (f ? 0 : 1);
  • If the field f is a byte, char, short or int: calculate (int)f;
  • If the field f is a long: calculate (int)(f ^ (f >>> 32));
  • If the field f is a float: calculate Float.floatToIntBits(f);
  • If the field f is a double: calculate Double.doubleToLongBits(f) and handle the return value like every long value;
  • If the field f is an object: Use the result of the hashCode() method or 0 if f == null;
  • If the field f is an array: see every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next.

将哈希值 c 结果组合:

result = 37 * result + c


  • 返回结果

    这应该会导致正确的分发大多数使用情况下的哈希值。

    This should result in a proper distribution of hash values for most use situations.

    这篇关于集合的hashCode方法的最佳实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆