重写equals要遵照的规则

首先要注意重写equals必须重写hashCode
(1.1)自反性:对于任何非null的引用值x,x.equals(x)=true
(1.2)对称性:对于任何非null的引用x,y,x.equals(y)=true,一样y.equals(y)=true
(1.3)传递性:对于任何非null的引用x,y,z,x.equals(y)=true,x.equals(z)=true =>y.equals(z)=true
(1.4)一致性:对于任何非null的引用x和y,只要equals的操做涉及的类信息没有改变,则x.equals(y)的结果一直不变;
对于任何为null的引用,null.equals(x)=false

重写equals方法的四个步骤:

(1)使用==操做符判断参数是不是这个对象的引用; (2)使用instanceof操做符判断”参数是不是正确的类型“; (3)把参数装换成正确的类型; (4)对于参数中的各个域,判断其是否和对象中的域相匹配;
示例以下:
public class PhoneNumber {
    private final short areaCode;
    private final short prefix;
    private final short lineNumber;

    public PhoneNumber(int areaCode, int prefix, int lineNumber) {

        this.areaCode = (short) areaCode;
        this.prefix = (short) prefix;
        this.lineNumber = (short) lineNumber;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof PhoneNumber)) {
            return false;
        }
        PhoneNumber ph = (PhoneNumber) obj;
        return ph.areaCode == areaCode && ph.prefix == prefix && ph.lineNumber == lineNumber;
    }