深入equals方法
equals方法的重要性毋須多言,只要你想比較的兩個(gè)對(duì)象不愿是同一對(duì)象,你就應(yīng)該實(shí)現(xiàn)
equals方法,讓對(duì)象用你認(rèn)為相等的條件來(lái)進(jìn)行比較.
下面的內(nèi)容只是API的規(guī)范,沒(méi)有什么太高深的意義,但我之所以最先把它列在這兒,是因?yàn)?BR>這些規(guī)范在事實(shí)中并不是真正能保證得到實(shí)現(xiàn).
1.對(duì)于任何引用類型, o.equals(o) == true成立.
2.假如 o.equals(o1) == true 成立,那么o1.equals(o)==true也一定要成立.
3.假如 o.equals(o1) == true 成立且 o.equals(o2) == true 成立,那么
o1.equals(o2) == true 也成立.
4.假如第一次調(diào)用o.equals(o1) == true成立再o和o1沒(méi)有改變的情況下以后的任何次調(diào)用
都成立.
5.o.equals(null) == true 任何時(shí)間都不成立.
以上幾條規(guī)則并不是最完整的表述,具體的請(qǐng)參見(jiàn)API文檔.
對(duì)于Object類,它提供了一個(gè)最最嚴(yán)密的實(shí)現(xiàn),那就是只有是同一對(duì)象是,equals方法才返回
true,也就是人們常說(shuō)的引用比較而不是值比較.這個(gè)實(shí)現(xiàn)嚴(yán)密得已經(jīng)沒(méi)有什么實(shí)際的意義,
所以在具體子類(相對(duì)于Object來(lái)說(shuō))中,假如我們要進(jìn)行對(duì)象的值比較,就必須實(shí)現(xiàn)自己的
equals方法.
先來(lái)看一下以下這段程序:
public boolean equals(Object obj)
{
if (obj == null) return false;
if (!(obj instanceof FieldPosition))
return false;
FieldPosition other = (FieldPosition) obj;
if (attribute == null) {
if (other.attribute != null) {
return false;
}
}
else if (!attribute.equals(other.attribute)) {
return false;
}
return (beginIndex == other.beginIndex
&& endIndex == other.endIndex
&& field == other.field);
}
這是JDK中java.text.FieldPosition的標(biāo)準(zhǔn)實(shí)現(xiàn),似乎沒(méi)有什么可說(shuō)的.
我信相大多數(shù)或絕大多數(shù)程序員認(rèn)為,這是正確的合法的equals實(shí)現(xiàn).究竟它是JDK的API實(shí)現(xiàn)啊.
還是讓我們以事實(shí)來(lái)說(shuō)話吧:
package debug;
import java.text.*;
public class Test {
public static void main(String[] args) {
FieldPosition fp = new FieldPosition(10);
FieldPosition fp1 = new MyTest(10);
System.out.PRintln(fp.equals(fp1));
System.out.println(fp1.equals(fp));
}
}
class MyTest extends FieldPosition{
int x = 10;
public MyTest(int x){
super(x);
this.x = x;
}
public boolean equals(Object o){
if(o==null) return false;
if(!(o instanceof MyTest )) return false;
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注