gpt4 book ai didi

java - 比较两个不同对象的不同列表中的元素

转载 作者:行者123 更新时间:2023-11-29 05:53:03 26 4
gpt4 key购买 nike

我会发布我的代码,但只是更改名称。当我可以添加更多信息时,我会添加评论。

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。所以它们是不同的对象,我认为这可能是问题所在。

有什么建议吗?抱歉,如果这非常含糊...

我的主要问题是,如果我想比较这两个列表中的元素,最好的方法是什么?

最佳答案

List.contains(...)使用 equals()用于比较:

More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==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)。

如果您发现自己经常这样做,那么他们都实现的抽象类可能会有所帮助。

关于java - 比较两个不同对象的不同列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com