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之所有对象的公用方法>9.Always override hashCode when you override equals

     You must override hashCode in every class that overrides equals.

  4. Effective Java —— 覆盖equals时总要覆盖hashCode

    本文参考 本篇文章参考自<Effective Java>第三版第十一条"Always override hashCode when you override equals&quo ...

  5. 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 ...

  6. Effective Java 目录

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

  7. Effective Java —— 覆盖equals时遵守通用约定

    本文参考 本篇文章参考自<Effective Java>第三版第十条"Obey the general contract when overriding equals" ...

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

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

  9. Effective Java 第三版——11. 重写equals方法时同时也要重写hashcode方法

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

随机推荐

  1. java抽象类和接口区别

    深入理解Java的接口和抽象类 对于面向对象编程来说,抽象是它的一大特征之一.在Java中,可以通过两种形式来体现OOP的抽象:接口和抽象类.这两者有太多相似的地方,又有太多不同的地方.很多人在初学的 ...

  2. 一秒钟生成自己的iOS客户端

    原谅我这个标题党 想当年我也是亲自学过几天Objective-c的程序猿,我一眼就知道我是在骗人,但那有怎样呢!还不是满大街都是各种<十分钟让你明白Objective-C的语法>.< ...

  3. C#序列化JSON

    public static string ConvertToJsonString<T>(T instance) {             using (MemoryStream stre ...

  4. mysqldump: Couldn't execute 'show table status '解决方法

    执行:[root@host2 lamp]# mysqldump -F -R -E --master-data=2   -p -A --single-transaction 在控制台端出现 mysqld ...

  5. Github教程(2)

    一些小技巧: 在Github的个人主页中按Shift+/ 可以显示快捷键的操作: 在某个项目的文件列表中,按下t,即可根据输入的文件名和部分文件名查找文件: 对比两个分支之间的差别,以mybatis项 ...

  6. vs.net_2003 下载 虽然是老古董了,但还是很有用的。

    系统要求 支持的操作系统: Windows 2000; Windows NT; Windows Server 2003; Windows XP 以下VS2003的下载链接: http://bcsoft ...

  7. 模拟浏览器搜索功能(Ctrl + F)

    写的匆忙,示意一下,有待完善.把以下代码复制到文本文件中,把文件扩展名改为.html就可以运行了. <html> <head> <style type="tex ...

  8. sencha treestore 取消自动加载数据

    gridstore在设置了autoLoad=false后不会自动加载数据,但是treestore不行,后来发现删掉root里的expanded:true后就可以了.但是界面上树没有展开,需在store ...

  9. vs2012 编译运行报 项目程序包Dsp.Bds.dll还原失败,找不到版本xxxxxx的程序包问题的解决方法

    原先vs2012程序运行项目是可以了,不会出现程序包Dsp.Bds.dll还原失败,找不到版本未2.0.1.0的程序包问题, 但是项目可以正常运行,每次调试看到下面一片红感觉不舒服 原因:可能当时我看 ...

  10. wpf 查找页面的所有TextBox

    private void EnumVisual(Visual myVisual) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount( ...