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的更多相关文章

  1. 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 ...

  2. 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 ...

  3. 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 ...

  4. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  5. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  6. Effective Java —— 覆盖equals时遵守通用约定

    本文参考 本篇文章参考自<Effective Java>第三版第十条"Obey the general contract when overriding equals" ...

  7. Effective Java Methods Common to All Objects

    Obey the general contract when overriding equals 先了解equals 和 == 的区别,如果不重写equals, equals比较的仅仅只是是否引用同一 ...

  8. 《Effective Java》读书笔记 - 3.对于所有对象都通用的方法

    Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...

  9. Effective Java 12 Consider implementing Comparable

    Sort array with sorted collection construction. public class WordList { public static void main(Stri ...

随机推荐

  1. 新找到一个安装Android SDk的方法-记录

    此方法需使用国内的镜像,但是国内镜像网速不一定要很快. 迅雷下载工具这个是必须的. 今天注意到SDK目录下有一个temp文件夹,打开看了看发现就是缓存的目录,因此想到直接从镜像站下载相应的包来替换,测 ...

  2. CentOS6.5菜鸟之旅:文件权限详解

    一.前言 Linux下所有资源.设备均被视作文件来操作,而文件权限则是决定用户可各文件操作的范围,无论是平时使用Linux,还是写程序均涉及这方面.以下为个人学习的整理,供以后查阅. 二. 三种权限 ...

  3. Qt之QAbstractItemView视图项拖拽(一)

    一.需求说明 最近在搞视图项的拖拽,也上网查了一些资料,好多的文档都是一样的,只是被不通的网站所收录了(也有可能是被爬过去的,不明所以),不过也有一些文档写的不错,不过就是太简易,都是点睛之笔,总之功 ...

  4. 0422 发现( 数学口袋精灵)bug

    团队博客地址: 甘佳萍:http://www.cnblogs.com/gjpg/ 李鹏飞:http://www.cnblogs.com/l549023320/ 赵创佳:http://www.cnblo ...

  5. 用Qt写软件系列三:一个简单的系统工具之界面美化

    前言 在上一篇中,我们基本上完成了主要功能的实现,剩下的一些导出.进程子模块信息等功能,留到后面再来慢慢实现.这一篇来讲述如何对主界面进行个性化的定制.Qt库提供的只是最基本的组件功能,使用这些组件开 ...

  6. 对一个或多个实体的验证失败。有关详细信息,请参见“EntityValidationErrors”属性。

    问题原因: 1.非空列未插入值错误 2.内容长度超过列最大长度(超过数据库设置长度,或者自定义长度“[StringLength(50, MinimumLength = 6, ErrorMessage ...

  7. onclick事件与onserverclick事件

    1.这里仅对web控件而言,onclick事件执行的是客户端中的代码, <%@ Page Language="C#" AutoEventWireup="true&q ...

  8. EntityFramework left join

       var result = from u in db.Order                              join n in db.Equipment on u.OrderId  ...

  9. 平衡二叉树---Shaolin

    Description Shaolin temple is very famous for its Kongfu monks.A lot of young men go to Shaolin temp ...

  10. 关于我的OI生涯(AFO){NOIP2016 后}

    这篇我就随意写啦~不用统一的“题解”形式.♪(^∀^●)ノ 也分好几次慢慢更吧~ 对于NOIP2016的总结,我本想善始善终back回,但是心情不足以支撑我,那就只能有始有终了......下面进入我的 ...