天天看點

JAVA-重寫equalse規範、技巧

JAVA-重寫equalse規範、技巧

1、自反性
任何非空引用x,x.equalse(x) 應該傳回true
           
2、對稱性
任何引用x和y,當x.equals(y)傳回true,y.equals(x)也應傳回true
           
3、傳遞性
任何引用x、y和z,當x.equalse(y)和y.equalse(z),那麼x.equalse(z)也應傳回true
           
4、一緻性
如果x和y引用的對象沒有發生任何變化,那麼反複x.equals(y)都應傳回一樣的結果
           
5、任何非空引用 x.euqals(null) 都應傳回 false
6、重寫equalse時,也要重寫hashCode方法
equalse和hashCode定義必須一緻,當x.equalse(y) 為true,那麼x.hashCode()必須等于y.hashCode();
           
import java.util.Objects;

public class Parent {
}

class SubObject extends Parent {

    private String name;

    @Override
    public boolean equals(Object otherObject) {
        //檢測this和otherObject是否是同一個對象
        if (this == otherObject) return true;
        //null一律傳回 false
        if (otherObject == null) return false;

        //是否是同一類型,擇一
        if (getClass() != otherObject.getClass()) return false;//1、當需要判斷具體類型時
        if (!(otherObject instanceof Parent)) return false;//2、本類及其子類均可

        //将otherObject轉換相應對象
        SubObject other = (SubObject) otherObject;

        //比較域,根據業務需求
        Objects.equals(this.name, other.name);

        return true;
    }

    @Override
    public int hashCode() {
        //如果equalse方法比較的是name,那麼hashCode方法就要散列name
        return Objects.hash(name);
    }
}           

繼續閱讀