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;@Overridepublic boolean equals(Object otherObject) {//檢測this和otherObject是否是同一個對象if (this == otherObject) return true;//null一律返回 falseif (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;}@Overridepublic int hashCode() {//如果equalse方法比較的是name,那么hashCode方法就要散列namereturn Objects.hash(name);}
}