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. Mysql大量插入随机数据方法--存储过程

    创建测试表: mysql)); 创建存储过程: mysql> delimiter // mysql> create procedure rand_data(in num int) -> ...

  2. java和javascript双引号嵌套的问题

    双引号不能嵌套双引号,否则一对双引号就结束了. java中双引号中嵌套双引号需要转义: /** * java双引号转义符测试 * @author asus * */ public static voi ...

  3. Linux平台Qt creator报错:Circular all <- first dependency dropped

    在Linux下安装好Qt 5.0之后,使用Qt Creator创建了一个基于QMainWindow的框架程序.原本应该可以顺利的完成编译工作,因为自带的模板工程没有经过任何修改.可是在编译整个工程的时 ...

  4. 2014 Asia AnShan Regional Contest --- HDU 5078 Osu!

    Osu! Problem's Link:   http://acm.hdu.edu.cn/showproblem.php?pid=5078 Mean: 略. analyse: 签到题,直接扫一遍就得答 ...

  5. Vector Clock/Version Clock

    physical clock 机器上的物理时钟,不同的机器在同一个时间点取到的physical clock不一样,之间会存在一定的误差,NTP可以用来控制这个误差,同一个机房内的机器之间的时钟误差可以 ...

  6. Winform开发框架之权限管理系统改进的经验总结(4)--用户分级管理

    在实际的系统应用环境中,用户的分级管理一般也是比较常见的功能,小的业务系统可以不需要,但是一般涉及到集团.分子公司.或者是事业单位里面的各个处室或者某某局的人员管理,这些分级管理就显得比较必要,否则单 ...

  7. 客户关系管理系统(CRM)的开发过程中使用到的开发工具总结

    开发<客户关系管理系统(CRM)>软件过程,也就是一个标准的Winform程序的开发过程,我们可以通过这个典型的软件开发过程来了解目前的开发思路.开发理念,以及一些必要的高效率手段.本篇随 ...

  8. 【百度SEO优化】如何让蜘蛛爬行你的网站

    大家都知道,现在做网站简单,但是推广就比较困难了,可能一些商家引入投资,直接烧钱做广告来推广,但是对于一些小站长,是没有那么多资金的.因此我们就要懂得一些SEO优化的知识了,简单介绍一下: 怎么让百度 ...

  9. C#开发中可能会用到的一些小贴士(转)

    转至http://www.cnblogs.com/Ebony-Ivory/p/4380106.html C#篇: 1.目标平台的选择 64位操作系统在编译VS里的程序时,根据需要设置项目属性的“目标平 ...

  10. FL2440驱动添加(4)LED 驱动添加

    硬件信息:FL2440板子,s3c2440CPU带四个LED,分别在链接GPB5,GPB6,GPB8,GPB10 内核版本:linux-3.8.0 led驱动代码如下: 值得注意地方地方: 1,定时器 ...