equals 方法
Object 類中的 equals 方法用於檢測一個對象是否等於另外一個對象。在 Object 類中,這
個方法將判斷兩個對象是否具有相同的引用。如果兩個對象具有相同的引用, 它們一定是相
等的。從這點上看,將其作為默認操作也是合乎情理的。然而,對於多數類來說, 這種判斷
並沒有什么意義。例如, 采用這種方式比較兩個 PrintStream 對象是否相等就完全沒有意義。
然而, 經常需要檢測兩個對象狀態的相等性,如果兩個對象的狀態相等, 就認為這兩個對象
是相等的。
例如, 如果兩個雇員對象的姓名、 薪水和雇佣日期都一樣, 就認為它們是相等的(在實
際的雇員數據庫中,比較 ID 更有意義。利用下面這個示例演示 equals 方法的實現機制)。
public class Employee public boolean equals(Object othe「Object) { // a quick test to see if the objects are identical if (this == otherObject) return true; // must return false if the explicit parameter is null if (otherObject == null) return false; // if the classes don't match, they can't be equal if (getClassO != otherObject.getClass()) return false; // now we know otherObject is a non-null Employee Employee other = (Employee) otherObject; // test whether the fields have identical values return name.equals(other. name) && salary = other,sal ary && hi reDay. equals(other,hi reDay):
}
}