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. 测试Flask应用_学习笔记

    源代码尽在我的github上面:https://github.com/521xueweihan 欢迎大家交流学习 """ setUp() 方法中会创建一个新的测试客户端并 ...

  2. Cocos2dx-3.0版本 从开发环境搭建(Win32)到项目移植Android平台过程详解

    作为重量级的跨平台开发的游戏引擎,Cocos2d-x在现今的手游开发领域占有重要地位.那么问题来了,作为Cocos2dx的学习者,它的可移植特性我们就需要掌握,要不然总觉得少一门技能.然而这个时候各种 ...

  3. 通过LINQ表达式树动态构建查询条件

    第一种方法: public static class PredicateExtensions { public static Expression<Func<T, bool>> ...

  4. C#使用基类的引用 and 虚方法和覆写方法

    结论:使用基类的引用,访问派生类对象时,得到的是基类的成员. 虚方法和覆写方法

  5. C#属性封装

    1.属性封装是为了保护与之相对应的字段的,保证字段的读取和赋值是否符合要求 2.属性可以分为:读写,只读,只写 3.允许外部访问的变量一定要申明为属性 4.属性的本质就是两个方法. 5.自动属性 6. ...

  6. 微软modern.IE网站,多版本IE免费测试工具集

    微软今天发布了modern.IE,这是一系列免费的.针对Web 开发者的测试工具和资源集合网站,微软希望以此来帮助开发者更轻松地实现跨 IE 和其他现代浏览器.跨设备的兼容性,其他还有代码检测工具.标 ...

  7. .NET开发 正则表达式中的 Bug

    又发现了一个 .net 的 bug!最近在使用正则表达式的时候发现:在忽略大小写的时候,匹配值从 0xff 到 0xffff 之间的所有字符,正则表达式竟然也能匹配两个 ASCII 字符:i(code ...

  8. 重新想象 Windows 8 Store Apps (66) - 后台任务: 下载和上传

    [源码下载] 重新想象 Windows 8 Store Apps (66) - 后台任务: 下载和上传 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 后台任务 后台 ...

  9. php中设定一个全局异常处理。全局catch。默认catch。默认异常处理

    <?php function handleMissedException($e) { echo "Sorry, something is wrong. Please try again ...

  10. winform(多窗体、菜单和工具栏)

    一.多窗体 1.哪个是主窗体 利用From1的button将From2打开 private void button1_Click(object sender, EventArgs e) { Form2 ...