读书笔记-《Effective Java》第8条:覆盖equals时请遵守通用约定

如果覆盖equals方法的目的是判断对象之间是否相等,那么使用超类(Object)的方法即可。

 public boolean equals(Object obj) {
        return (this == obj);
    }

在覆盖equals方法的时候,必须要遵守它的通用约定:

  • 自反性(reflexive)。对于任何非null的引用值x,x.equals(x)必须返回true。
  • 对称性(symmetric)。对于任何非null的引用值x和y,y.equals(x)返回true,那么xequals(y)也必须返回true
  • 传递性(transitive)。对于任何非null的引用值x、y、z,x.equals(y)返回true,并且y.equals(z)返回true,那么x.equals(z)也必须​​​​​​​返回true。
  • 一致性(consistent)。对于任何非null的引用值x和y,只要equals的比较操作所用到的信息没有被修改,那么多次调用equals方法结果必须与第一次调用保持一致。
  • 非空性。这个在equals中是要首先判断的。

重写equals方法的诀窍:

  • 使用==操作符检查“参数是否为这个对象的引用”。 性能的优化。
  • 使用instanceof操作符检查“参数是否为正确的类型”。
  • 把参数转换成正确的类型
  • 对于该类中的每个“关键”域,检查参数中的域是否与该对象中的域相匹配。
  • 编写完成equals方法后,要检查、测试是否符合约定。
  • 覆盖equals时总要覆盖hashCode。
  • 不要企图equals方法过于智能。
  • 不要将equals声明中的Object对象替换为其他的类型。 @Override

jdk 1.8中String类的equals方法

   /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

猜你喜欢

转载自blog.csdn.net/baitianmingdebai/article/details/85244847