JDK提供的工具類
Object :: equals
public boolean equals(Object otherObj){
return this == otherObj;
}
比較存儲地址是否相等。
String :: equals
public boolean equals(String anObj){
if(this == anObj) return true;
if( anObj instanceof String ) { // 如果anObj爲null,instanceof爲false; // String 爲final的沒有子類,因此適合用instanceof
String other = (String) anObj;
int n = value.length;
if( n == other.value.length){
char [] v1 = value;
char [] v2 = other.value;
int i=0;
while( n--!=0 ){
if(v2[i]!=v2[i]) return false;
i++;
}
return true;
}
}
return false;
}
Objects :: equals
public static boolean equals(Object a,Objectb){
return (a==b) || (a!=null) && a.equals(b);
}
自定義類的equals方法一般實現
- 如果有父類的實現,首先
if(!super.equals()) return false;
- 如果沒有父類,首先
if( this == otherObj) return true;
- 如果沒有父類,再判斷
if(otherObj == null ) return false;
- 如果沒有父類,並且當前類不是fianl的,用
if( !(getClass()==otherObj.getClass())) return false;
判斷是否相同類型 - 最後對兩個對象的域的值進行判斷,對於複雜數據類型的域,要用Objects.equals(a,b)去比較,以防NullException
- 根據Object類對equals方法的定義的逆反性規則,如果類不是final的,用if( getClass() == other.getClass())比較兩者是否同一個類,而非用instanceof來判斷。原因:
前提:class B extends A
,有A的實例a,B的實例b,
規則要求:a.equals(b) <=> b.equals(a) ;即如果a.equals(b)爲true,那麼必然b.equals(a)也爲true;
instanceof:
class A { ... if( otherObj instanceof A) ...}
class B extends A { ... if( otherObj instanceof B) ...}
//這種情況下 a.equals(b)有可能爲true,因爲B是A的子類,b instanceof A爲true。
// 而b.equals(a)則一定爲flase,因爲A是B的父類。a instanceof b 一定爲false
// 則 違反了可逆規則。
實例:
/**
僱員類
*/
public class Employee{
private String name;
private double salray;
private LocalDate hireDay;
...
public boolean equals(Object otherObj){
if(this == otherObj) return true;
if(otherObj == null) return false;
if(getClass() == otherObj.getClass()){
Employee other = (Employee)otherObj;
return Objects.equals(name,other.name) &&
(salary == other.salary) &&
Objects.equals(hireDay, other.hireDay)
}
return false;
}
}
/**
管理人員
*/
public class Manager extends Employee{
private double bonus; // 績效獎金
...
public boolean equals(Object otherObj){
if(!super.equals(otherObj)) return false;
Manager other = (Manager)otherObj;
return bonus == other.bonus;
}
}