2010-09-21 95 views
1

如何比較基類對象與派生類中的派生類對象?我需要得到true作爲輸出從下面的代碼:如何將派生類對象與基類對象java進行比較?

class Base { 
    int i; 
    String str; 
} 

class Derived extends Base{ 
    double d; 
    String str1; 

    public static void main(String []a){ 
     Base b= new Base(); 
     Derived d = new Derived(); 
     System.out.println("Equals! :"+d.equals(b)); 
    } 
} 

它總是給我false作爲輸出。我如何比較基類和派生類?

回答

1

通常爲同一類的對象定義對象相等性,例如:您可能希望兩個對象Base b1, b2在它們相同時stri值相等,那麼你就需要定義equals()(並且通常hashCode())方法來測試這種情況,例如:。

public boolean equals(Object obj) 
{ 
    // test for identity 
    if (this == obj) return true; 

    // check that obj is not null, and that it is an instance of Base 
    if (obj == null) return false; 
    if (getClass() != obj.getClass()) return false; 

    // compare attributes 
    Base other = (Base) obj; 
    if (i != other.i) return false; 
    if (str == null && other.str != null) return false; 
    if (!str.equals(other.str)) return false; 
    return true; 
} 

在你的情況下,由於BaseDerived屬於不同類別,具有不同的屬性(Basestri,而Derivedstr,i,str1d),您需要準確定義對象BaseDerived的對象應該是什麼時候相等。

1

好,使它只返回true是很容易的:

@Override 
public boolean equals(Object other) { 
    return true; 
} 

但是,我認爲,這不是你應該做什麼(即使是在不那麼簡單的實現)。

我認爲equals方法從Object不應該返回true,除非類型實際上是相同的。否則,最終會讓生活變得非常棘手,以確保滿足Object.equals(Object)所要求的對稱性。它也不覺得它是滿足自然當時的平等。

但是,編寫一個能夠比較任何兩個Base實例在您的具體情況下相等的類是完全合理的。關於平等比較者的好處是,他們不必像自然一樣自然 - 你並沒有定義什麼樣的平等意味着整個類型 - 你只是描述了一個具體的比較。

不幸的是,Java沒有EqualityComparator<T>(或其他)接口去Comparator<T>。這使得創建(比如說)地圖和設置使用特定平等思想(以及散列代碼)的難度更大。這可能會也可能不會成爲你的問題 - 你希望如何使用這種平等比較呢?如果它在你自己的代碼中,你可以編寫你自己的EqualityComparator<T>界面。如果您要構建地圖或集合,它不會那麼容易:(