Effective Java 09 Always override hashCode when you override equals
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的更多相关文章
- 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 ...
- Effective Java 第三版——40. 始终使用Override注解
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Java之所有对象的公用方法>9.Always override hashCode when you override equals
You must override hashCode in every class that overrides equals.
- Effective Java —— 覆盖equals时总要覆盖hashCode
本文参考 本篇文章参考自<Effective Java>第三版第十一条"Always override hashCode when you override equals&quo ...
- 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 ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- Effective Java —— 覆盖equals时遵守通用约定
本文参考 本篇文章参考自<Effective Java>第三版第十条"Obey the general contract when overriding equals" ...
- 《Effective Java》读书笔记 - 3.对于所有对象都通用的方法
Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...
- Effective Java 第三版——11. 重写equals方法时同时也要重写hashcode方法
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
随机推荐
- ASP.NET在不同情况下实现单点登陆(SSO)的方法
第一种:同主域但不同子域之间实现单点登陆 Form验证其实是基于身份cookie的验证.客户登陆后,生成一个包含用户身份信息(包含一个ticket)的cookie,这个cookie的名字就是在web. ...
- JavaScript一些函数
1.prompt()函数:有两个参数,一个是显示用户输入框上面的标签,另一个是输入框的初始值.用来接收用户输入的值,然后把它返回到代码中: 例如: <doctype html> <h ...
- JS代码的位置与事件响应代码块的封装问题
JS代码的位置 我们可以将JavaScript代码放在html文件中任何位置,但是我们一般放在网页的head或者body部分. 放在<head>部分最常用的方式是在页面中h ...
- .net中清理内存,清理占用内存方式方法
#region 内存回收 [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize") ...
- c# 文件另存为代码
利用.NET中的File.Copy方法 命名空间:System.IO 重载列表:Copy(string sourceFilePath,string targetFilePath) sourceFile ...
- C# SortedList类概念和示例
SortedList 类 [C#] 命名空间: System.Collections 表示键/值对的集合,这些键和值按键排序并可按照键和索引访问. SortedList 是 Hashtable 和 A ...
- ActiveReports 报表应用教程 (5)---解密电子商务领域首张电子发票的诞生(套打报表)
6月27日京东商城发布了中国电子商务领域首张电子发票,同时宣布相关系统正式上线,这标志着中国电子商务的步伐又向前迈出了重要的一步.目前“电子发票”覆盖的服务范围是在北京地区购买图书.音像商品的个人消费 ...
- JavaSE——TCP网络编程(二)
ServerSocket 类与Socket 类的不同用法: ServerSocket类: 创建一个ServerSocket类,同时在运行该语句的计算机的指定端口处建立一个监听服务,如: Serv ...
- Yii2学习笔记之场景
场景 一个模型可能在多个场景中使用,在不同的场景中,模型可能使用不同的业务逻辑和规则.例如, User 模型可能在用户登录时使用,也可能在用户注册时使用,某些属性可能在用户注册时强制要求有,在用户登录 ...
- 【iOS】Quartz2D练习-动态改变属性值
一.通过slider控制圆的缩放 1.实现过程 新建一个项目,新建一个继承自UIview的类,并和storyboard中自定义的view进行关联.代码示例:SLViewController.m文件 # ...