hashCode方法的最佳实现 [英] Best implementation for hashCode method

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

问题描述

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

解决方案

最佳实施?这是一个很难回答的问题,因为它取决于使用模式。



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



短版




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


  2. equals()中测试的每个字段 f / code>方法,计算一个哈希码 c 如果字段f是布尔值
    计算(f?0:1);


  3. 如果字段f是字节 char int :calculate (int)f ; $ b $如果字段f是 long :calculate (int)(f ^(f>>> 32));

  4. 如果该字段f是:计算 Float.floatToIntBits( f);

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

  6. 如果字段f是一个对象:使用 hashCode()方法或0如果 f == null ;

  7. 如果字段f是一个数组字段作为单独的元素,并以递归方式计算散列值,并按照下面的描述合并这些值。

  8. 结合散列值 c result

     结果= 37 *结果+ c 


  9. 返回结果


这应该导致适当的分配散列值适用于大多数使用情况。

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.

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.

A short version

  1. Create a int result and assign a non-zero value.

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

    • 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.
  3. Combine the hash value c with result:

    result = 37 * result + c
    

  4. Return result

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

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

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