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. [python]pip常用命令(转载)

    用阿里云服务器,使用pip安装第三方库的时候卡的要死.所以我就想pip能不能安装本地的包. 找到了这篇博客: http://me.iblogc.com/2015/01/01/pip%E5%B8%B8% ...

  2. IT168关于敏捷开发采访

    1.我们知道敏捷开发是一套流程和方法的持续改进,通过快速迭代的方式交付产品,从而控制和降低成本.但是在实行敏捷初期,往往看不到很好的效果.这里面,您觉得问题主要出在哪?团队应如何去解决问题?金根:我认 ...

  3. 使用fat-jar打包多个java工程为可执行文件

    对于一个从C++转向Java的程序员来说,制作java的可执行文件,也算是比较棘手的问题.项目是前几个同事留下来的,几个必备的库文件和制作可执行文件的工具居然都是加密未解封的:不知道是不是因为公司和前 ...

  4. Windows及Linux平台下的计时函数总结

    本文对Windows及Linux平台下常用的计时函数进行总结,包括精度为秒.毫秒.微秒三种精度的各种函数.比如Window平台下特有的Windows API函数GetTickCount().timeG ...

  5. .Net魔法堂:发个带附件的邮件

    一.前言   由于工作需要最近把邮件发送封装成WebService,现在把代码记录在此,以便日后查阅. 二.二话不说写代码 private void _SendMail(string form, st ...

  6. 移动web开发总结

    让网页的宽度自适应屏幕<meta name="viewport" content="width=device-width"/>   1)html上加 ...

  7. 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo

    [源码下载] 重新想象 Windows 8 Store Apps (34) - 通知: Toast Demo, Tile Demo, Badge Demo 作者:webabcd 介绍重新想象 Wind ...

  8. 【Java Saves!】Session 5:计算机器之三--二指禅

    人有十指.人类掰着手指头,发明出了0.1.2-9这十个数字.后来手指头不够用了,便发明出数位(个.十.百.千-)和满十进一的规则,称为十进制. 而计算机靠两个手指头工作.在计算机内部,只有0和1两个数 ...

  9. ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var mysql 启动不了

    ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var mysql 启动不了   ps -A | gr ...

  10. Python可变参数

    #!/usr/bin/env python # -*- coding: utf-8 -*- import math def calc(*numbers): sum=0 for n in numbers ...