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 class is inherently unique.
2. You don't care whether the class provides a "logical equality" test.
3. If a superclass has already overridden equals, and the superclass behavior is appropriate for this class.
4. The class is private or package-private, and you are certain that its equals method will never be invoked.
Arguably, the equals method should be overridden under these circumstances, in case it is accidentally invoked:
@Override public boolean equals(Object o) {
throw new AssertionError();
// Method is never called
}
When a class has a notion of logical equality that differs from mere object identity, and a superclass has not already overridden equals to implement the desired behavior.
The equals method implements an equivalence relation. It is:
• Reflexive: For any non-null reference value x, x.equals(x)must return true.
• Symmetric: For any non-null reference values x and y, x.equals(y)must return true if and only if y.equals(x) returns true.
@Override public boolean equals(Object o) {
return o instanceof CaseInsensitiveString &&
((CaseInsensitiveString) o).s.equalsIgnoreCase(s);
}
• Transitive: For any non-null reference values x, y, z, if x.equals(y)returns
True and y.equals(z)returns true, then x.equals(z)must return true.
// Adds a value component without violating the equals contract
public class ColorPoint {
private final Point point;
private final Color color;
public ColorPoint(int x, int y, Color color) {
if (color == null)
throw new NullPointerException();
point = new Point(x, y);
this.color = color;
}
/**
* Returns the point-view of this color point.
*/
public Point asPoint(){
return point;
}
@Override public boolean equals(Object o) {
if (!(o instanceof ColorPoint))
return false;
ColorPoint cp = (ColorPoint) o;
return cp.point.equals(point) && cp.color.equals(color);
}
... // Remainder omitted
}
NOTE
Never use Timpstamp and java.util.Date class together in same collection since the Timpstamp does violate symmetry and can cause erratic behavior.
• Consistent: For any non-null reference values x and y, multiple invocations Of x.equals(y)consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
mutable objects can be equal to different objects at different times while immutable objects can't.
Java.net.URL's equals method relies on comparison of the IP addresses of the hosts associated with the URLs. Translating a host name to an IP address can require network access, and it isn't guaranteed to yield the same results over time.
• For any non-null reference value x, x.equals(null)must return false.
Recipe for a high-quality equals method
1. Use the ==operator to check if the argument is a reference to this object
2. Use the instanceof operator to check if the argument has the correct type
3. Cast the argument to the correct type
4. For each "significant" field in the class, check if that field of the argument
matches the corresponding field of this object
NOTE
If the type in step 2 is an interface, you must access the argument's fields via interface methods; if the type is a class, you may be able to access the fields directly, depending on their accessibility.
(field == null ? o.field == null : field.equals(o.field))
Primitive type: use == operator (float & double use Float.compare & Double.compare respectively to prevent -0.0).
Array fields: apply above guideline to each element ( If every element in an array field is significant, you can use one of the Arrays.equals)
5. When you are finished writing your equals method, ask yourself three
questions: Is it symmetric? Is it transitive? Is it consistent?
NOTE:
1. Always override hashCode when you override equals
2. Consistent use of the @Override annotation, as illustrated throughout this item, will prevent you from making this mistake (Item 36). This equals method won't compile and the error message will tell you exactly what is wrong:
@Override
public boolean equals(MyClass o) {
...
}
Effective Java 08 Obey the general contract when overriding equals的更多相关文章
- Java之所有对象的公用方法>8.Obey the general contract when overriding equals
Overriding the equals method seems simple, but there are many ways to get it wrong, and consequences ...
- 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 ...
- 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】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java —— 覆盖equals时遵守通用约定
本文参考 本篇文章参考自<Effective Java>第三版第十条"Obey the general contract when overriding equals" ...
- Effective Java Methods Common to All Objects
Obey the general contract when overriding equals 先了解equals 和 == 的区别,如果不重写equals, equals比较的仅仅只是是否引用同一 ...
- 《Effective Java》读书笔记 - 3.对于所有对象都通用的方法
Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...
- Effective Java 12 Consider implementing Comparable
Sort array with sorted collection construction. public class WordList { public static void main(Stri ...
随机推荐
- 利用栈实现算术表达式求值(Java语言描述)
利用栈实现算术表达式求值(Java语言描述) 算术表达式求值是栈的典型应用,自己写栈,实现Java栈算术表达式求值,涉及栈,编译原理方面的知识.声明:部分代码参考自茫茫大海的专栏. 链栈的实现: pa ...
- 十分钟搞懂什么是CGI
原文:CGI Made Really Easy,在翻译的过程中,我增加了一些我在学习过程中找到的更合适的资料,和自己的一些理解.不能算是严格的翻译文章,应该算是我的看这篇文章的过程的随笔吧. CGI真 ...
- sed用例
文件空行处理 1. 在文件中的每一行后面添加一个空行. sed 'G' test.txt 解释: Get命令是将保留空间的内容取出,并添加到当前模式空间的内容之后(添加一行).当保留空间为空时,效果为 ...
- SpringMVC核心——返回值问题
一.SpringMVC 使用 ModelAndView 来处理返回值问题. 1.ModelAndView 官方描述: Holder for both Model and View in the web ...
- 计数排序 + 线段树优化 --- Codeforces 558E : A Simple Task
E. A Simple Task Problem's Link: http://codeforces.com/problemset/problem/558/E Mean: 给定一个字符串,有q次操作, ...
- Ubuntu搭建Android交叉编译环境
一.下载 Android NDK Android NDK官方下载页:http://developer.android.com/tools/sdk/ndk/index.html如果需要旧版本的,比如10 ...
- UnityShader快速上手指南(四)
简介 由于其他项目中断了几天更新,继续~~ 这一篇主要是讲光照的(包含漫反射和高光以及多光源的处理) 还是先来看看具体效果(多光源后面单独展示) 有了基本的光照处理之后越来越有立体感了有不有 ╮(╯▽ ...
- URL与图像格式
绝对/相对URL “绝对URL”是指资源的完整的地址,通常以“http://”打头: “相对URL”是指Internet上资源相对于当前页面的地址,它包含从当前页面指向目标资源位置的路径,不以“htt ...
- 【JavaScript回顾】对象创建的几种模式
组合使用构造函数模式和原型模式 创建自定义类型的常见方式,就是组合使用构造函数模式与原型模式.构造函数模式用于定义实 例属性,而原型模式用于定义方法和共享的属性.结果,每个实例都会有自己的一份实例属性 ...
- BI之SSAS完整实战教程5 -- 详解多维数据集结构
之前简单介绍过多维数据集(Cube)的结构. 原来计划将Cube结构这部分内容打散,在实验中穿插讲解, 考虑到结构之间不同的部分都有联系,如果打散了将反而不好理解,还是直接一次性全部讲完. 本篇我们将 ...