equals 方法需要滿足的規范:
x.equals(x) 應該返回 true;x.equals(y) == true 時, y.equals(x) == true;x.equals(y) == true 和 y.equals(z) == true, 則 x.equals(z) == true;x.equals(null) == false;編寫 equals() 方法的建議:
@Override 注解, 重載父類 Object.equals(Object) 方法;Object otherObject, 稍後需要將它轉換成另一個叫做 other 的變量;this 與 otherObject 是否引用同一個對象;otherObject 是否為 null, 如果為 null, 返回 false;this 與 otherObject 是否屬於同一個類.equals 的語義在每個子類中有所改變, 那就要使用 getClass 檢測;otherObject 轉換為響應的類型變量 other;== 比較基本類型域, 使用 equals 比較對象域. 如果所有的域都匹配, 就返回 true, 否則返回 false;equals, 就要在其中調用 super.equals(otherObject), 如果返回 ture, 則繼續比較子類特有的域.在比較兩個對象是否相等時, 可使用 Objects.equals() 方法.
例如對於 Objects.equals(a, b):
ture;false;a.equals(b) 的返回值.如果重新定義了 equals 方法, 就必須重新定義 hashCode 方法, 以便用戶將對象插入到散列表中.hashCode 方法應該返回一個整型數值(也可以是負數), 並合理地組織實例域的散列碼, 以便能夠讓哥哥不同的對象產生的散列碼更加均勻.
Objects.hash(Object.. value) 可以傳遞多個參數並據此產生序列碼.
示例代碼:
import java.util.Objects;
public class TestEqualsAndHashCode {
private Object obj;
public Object getObj() {
return obj;
}
publicvoidsetObj(Object obj) {
this.obj = obj;
}
@Override
publicbooleanequals(Object otherObject) {
if (this == otherObject) {
return true;
}
if (null == otherObject) {
return false;
}
if (getClass() != otherObject.getClass()) {
return false;
}
TestEqualsAndHashCode other = (TestEqualsAndHashCode) otherObject;
return Objects.equals(getObj(), other.getObj());
}
@Override
publicinthashCode() {
return Objects.hash(obj);
}
publicstaticvoidmain(String[] args) {
TestEqualsAndHashCode a = new TestEqualsAndHashCode();
TestEqualsAndHashCode b = new TestEqualsAndHashCode();
a.setObj(1);
b.setObj(1);
System.out.println(Objects.equals(a, b));
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
}