Effective Java 09 Always override hashCode when you override equals

时间:2022-02-13 08:54:02

Failure to do so will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

Simple recipe for override hashCode

1. Store some constant nonzero value, say, 17, in an invariable called result.

2. For each significant field fin your object (each field taken into account by the

equalsmethod, that is), do the following:

a. Compute an inthash code cfor the field:

i. If the field is a boolean, compute (f?1:0).

ii. If the field is a byte,char, short, or int, compute (int) f.

iii. If the field is a long, compute (int) (f ^ (f >>> 32)).

iv. If the field is a float, compute Float.floatToIntBits(f).

v. If the field is a double, compute Double.doubleToLongBits(f), and then hash the resulting long as in step 2.

vi. If the field is an object reference and this class's equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If a more complex comparison is required, compute a "canonical representation" for this field and invoke hashCode on the canonical representation. If the value of the field is null, return 0(or some other constant, but 0 is traditional).

vii. If the field is an array, treat it as if each element were a separate field. That is, compute a hash code for each significant element by applying these rules recursively, and combine these values per step 2. If every element in an array field is significant, you can use one of the Arrays.hashCode methods added in release 1.5.

b. Combine the hash code c computed in step 2 into result as follows:

result = 31 * result + c;

3. Return result.

4. When you are finished writing the hashCode method, ask yourself whether equal instances have equal hash codes. Write unit tests to verify your intuition! If equal instances have unequal hash codes, figure out why and fix the problem.

NOTE

If a class is immutable and the cost of computing the hash code is significant, you might consider caching the hash code in the object rather than recalculating it each time it is requested.

// Lazily initialized, cached hashCode

private volatile int hashCode; // (See Item 71)

@Override public int hashCode() {

int result = hashCode;

if (result == 0) {

result = 17;

result = 31 * result + areaCode;

result = 31 * result + prefix;

result = 31 * result + lineNumber;

hashCode = result;

}

return result;

}

Effective Java 09 Always override hashCode when you override equals的更多相关文章

  1. Effective Java 08 Obey the general contract when overriding equals

    When it's the case that each instance of the class is equal to only itself. 1. Each instance of the ...

  2. Effective Java 第三版——40. 始终使用Override注解

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  3. Java之所有对象的公用方法&gt&semi;9&period;Always override hashCode when you override equals

     You must override hashCode in every class that overrides equals.

  4. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  5. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  6. 《Effective Java》读书笔记 - 3&period;对于所有对象都通用的方法

    Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...

  7. Effective Java 第三版——11&period; 重写equals方法时同时也要重写hashcode方法

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  8. Effective Java实作hashCode&lpar;&rpar; - 就是爱Java

    hashCode()这个方法,也是定义在Object class中,这个是所有class的base class,因此所有的class也都继承这个方法,预设是传回这个对象储存的内存地址编号,因为Mix覆 ...

  9. Effective java笔记(二),所有对象的通用方法

    Object类的所有非final方法(equals.hashCode.toString.clone.finalize)都要遵守通用约定(general contract),否则其它依赖于这些约定的类( ...

随机推荐

  1. U3D UGUI学习4 - Text

    1.对应NGUI的四种文字显示模式 Shrink Content 对应NGUI第一种模式     勾选Best Fit 但似乎有一个Bug,文字过多的时候会爆框.解决方法是改变Line Spacing ...

  2. ios layoutsubView 何时被调用

    -layoutSubviews方法:这个方法,在UIView中默认没有做任何事情,需要子类进行重写.UIView是一个纯净的视图,里面没有任何子控件,所以不会做什么事情.一般系统自带控件中有子控件的都 ...

  3. android输入法中的imeoption

    SDK升级到1.5以后,当文本输入框(EditText及其子类)获得焦点后,会弹出系统自带的软键盘 为了实现一些自定义的功能,就稍微研究了下 * 当layout中有多个EditText,把每个控件的a ...

  4. Request&period;Querystring中文乱码问题解决

    现象:近期项目中用到查询字符串传值,如果传递的是英文一切正常,但是传递中文时,使用request.querystring[]得到的是乱码. 原因:不知道为什么,可能是编码不一致问题 解决方法1:修改w ...

  5. mac 添加安卓设备的支持

    1. 把android设备插到mac电脑上 2. 首先可以看一下之前在该mac电脑上有没有添加过这个 , 命令 : adb devices      如果显示出,下面字样,说明之前添加过了,下面就可以 ...

  6. &lbrack;iOS基础控件 - 4&period;6&rsqb; iOS开发中的长度单位

    对于开发中设置的位置.尺寸单位 系统会根据屏幕的性质转换为像素单位 由于视网膜屏在同样尺寸下分辨率是非视网膜屏的两倍,所以 非视网膜屏:1个单位 = 1像素 视网膜屏:1个单位 = 2像素   应对非 ...

  7. c&plus;&plus; 14

    一.堆栈(stack) stack -> vector/deque/list push  -> push_back pop   -> pop_back top   -> bac ...

  8. 201521123082 《Java程序设计》第1周学习总结

    201521123082 <Java程序设计>第1周学习总结 标签(空格分隔): Java 1. 本周学习总结 0.初步了解Java语言及其发展历史和过程,同时也初步了解了Java具有跨平 ...

  9. this指向(匿名函数问题)

    1.匿名函数中 this一般指向window对象 2.闭包函数中的this,指向window var mod = { init: function(){ console.log('this',this ...

  10. JavaScript基础笔记(四) JS式面向对象

    JS式面向对象 一.理解对象 一)属性类型 ECMA-262 第 5 版在定义只有内部才用的特性(attribute)时,描述了属性(property)的各种特征. ECMA-262 定义这些特性是为 ...