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年出版,到现在已经将 ...
随机推荐
- [git]用pelican搞一个自己的blog(已完成)
pelican Pelican Static Site Generator, Powered by Python:Pelican是python语言写的静态网站生成器.因为我一直打算用github pa ...
- Hekaton的神话与误解
最近这段时间,我花了很多时间来更好的理解Hekaton——SQL Sever 2014里的全新内存表技术.我看了很多文章,了解了Haktaon的各种内部数据存储结构(主要是哈希索引和Bw-tree). ...
- MySqlConnection 并发连接的问题
最近在做项目的过程中遇到一个MySql在并发时初始化的问题,场景是这样子的: 我在Job中设定在同一时间点启动多个操作来访问数据库更新数据,结果在创建连接的时候抛出下面的问题: Note that w ...
- flex布局浅谈和实例
阿基米德曾说给我一个支点我可以撬动地球,而拥有flex基本可以撬动所有的布局. 1.flex布局基本介绍及效果展示 工欲善其事必先利其器,来来来,一起看下基础知识先(呵~,老掉牙,但是有用啊). ** ...
- Retention、Documented、Inherited三种注解
Retention注解 Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值:1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源 ...
- Xcode配置libdc1394
libdc1394是一个开源库,提供了一个Mac下完整的1394相机编程接口,这篇文章将介绍Xcode如何配置该库. 步骤: 1.下载libdc1394的源码,并解压 http://damien.do ...
- 将 C# 编译为原生机器码
C# 用户似乎都希望 C# 可以和 C++ 一样编译为本地的机器码.如果 C# 可以编译为机器码,将可以做到: 1. 效率提高,可以取代 C++ . 2. 反编译. 当然微软在商业利益的考虑下 ...
- 【GOF23设计模式】状态模式
来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_状态模式.UML状态图.酒店系统房间状态.线程对象状态切换 package com.test.state; public ...
- Swift 学习笔记第一天-变量常量,及数据类型
1.定义变量 用关键字 var 比如 var i=2 2.定义常量用let 如let c=3 可见Swift 定义时不用指定类型.由编译器推断 如果想指定类型 var i:Int32=2 练习 let ...
- UIMenuController的使用
1, 基本使用 以对一个UILabel长按弹出菜单为例 子类化UILabel 因为需要覆盖这几个方法:- (BOOL)canBecomeFirstResponder; 返回YES 同时需要在每次UI元 ...