2012-11-02 68 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,但这只是为了矫枉过正

相关问题