2012-11-02 71 views
1

我將發佈我的代碼,但只是更改名稱。當我可以添加更多信息時,我會添加評論。比較兩個不同列表中的元素是不同的對象

List<AbstractA> foo = bar.getFoo; // This returns an ArrayList<E> with two objects. Each object has an ID and Price. 

List<Name> names = null; 
try{ 
    names = someClass.getNames(); // This returns an ArrayList<E> with 10 Name objects. Each one has an ID, name, description 
}catch(Exception e){ 
    Log.warn(e); 
} 

我的主要目標是比較兩個列表。我有...

Iterator<Name> object = names.iterator(); 
while(object.hasNext()){ 
    Name j = object.next(); // assign next name 
    System.out.println("j.getId(): " + j.getId()); // This provides me the Id 
    System.out.println("foo.contains(j.getId()) " + foo.contains(j.getId())); // Keeps spitting out false but I want it to be true 

    if(foo.contains(j.getId())){ 
     object.remove(); //remove name out of Names list 
    } 
} 

我不知道這是否使我很想知道我在做什麼。 這個程序中有兩個bean代表foo和name。所以他們是不同的對象,我認爲這可能是問題。

有什麼建議嗎?對不起,如果這是非常模糊...

我的主要問題是,如果我想比較這兩個列表中的元素,最好的方法是什麼?

+1

提出問題。 – Mordechai

回答

2

List.contains(...)使用equals()其比較:

更正式地說,返回true當且僅當此列表包含至少一個元素e(O == NULLé== NULL:o.equals (E))。

equals()方法不需要兩個對象是同一類,這樣你就可以像這樣重寫它:

class Name { 

    // Stuff 

    @Override 
    bool equals(Object other) { 
     if(other instanceof Name) { 
      Name otherName = (Name)other; 
      // Compare this and otherName, return true or false depending 
      // on if they're equal 
     } else if (other instanceof AbstractA) { 
      AbstractA otherAbstractA = (AbstractA)other; 
      // Compare this and otherAbstractA, return true or false depending 
      // on if they're equal 
     } else { 
      return false; 
     } 
    } 
} 

你可能要覆蓋兩個equals()方法,使a.equals(b)== b.equals(a)。

如果你發現自己做了很多事情,可能它們都實現了一個抽象類將會有所幫助。

+0

這是在我正在執行此代碼的類中,還是在「bar」和「SomeClass」類中? – envinyater

+0

@envinyater你想要比較的兩個類。因此,無論類型出現在'foo'(您的示例中的'AbstractA')以及您將它與(Name是否爲j)進行比較的任何類型中,或者只是覆蓋AbstractA.getEquals()來處理字符串,如果您只想比較ID的。 –

+0

真的嗎?我懷疑它是一個好主意,聲稱像這樣'等於'一個'字符串'。另請參閱Josh Bloch關於甚至等於子類的評論:[最大的缺點是您得到的兩個對象看起來是平等的(因爲它們在所有字段上都是相等的),但它們並不相同,因爲它們具有不同的類。這可能會導致令人驚訝的行爲。](http://www.artima.com/intv/bloch17.html) –

0

您可能想要有兩個地圖而不是列表。

foo

key: id 
value: Object of AbstractA 

names

key: id 
value: Name object 

,那麼你可以比較鍵(在你的情況ID)

我希望我理解你的權利。

1

foo.contains(j.getId()))

fooList<AbstractA>j.getId()是(I猜)一個String。由於List.contains使用equals方法,因此這絕不會是true,除非您以奇怪的方式定義AbstractA.equals

最好的辦法是編寫自己的方法遍歷列表並進行比較。您可以使用Guava,但這只是爲了矯枉過正

相關問題