java 如何在java中比较两个不同的列表对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5282883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare two different list object in java?
提问by vinod
I have two class lists like List<Aclass>
A1 and List<Bclass>
b1 and both lists contain one field which is common. So by using this field I have to compare those two list? Please can anyone help me? Be ensure that those class lists are different.
我有两个类列表,如List<Aclass>
A1 和List<Bclass>
b1,并且两个列表都包含一个常见的字段。所以通过使用这个字段,我必须比较这两个列表?请任何人都可以帮助我吗?确保这些类列表是不同的。
回答by Aleadam
I'm not sure I fully understand the question, but you're asking for something like this?
我不确定我是否完全理解这个问题,但你是在问这样的问题吗?
public boolean compare (List<AClass> listA, List<BClass> listB) {
if (listA.size() != listB.size () return false;
for (int i=0; i<listA.size(); i++) {
AClass aClass == (AClass) listA.get(i);
BClass bClass == (BClass) listB.get(i);
if (aClass.commonField != bClass.commonField) return false;
}
return true;
}
Both lists should be sorted by that commonField field
两个列表都应按该 commonField 字段排序
回答by krock
Checkout the javadoc for List.equals():
two lists are defined to be equal if they contain the same elements in the same order.
如果两个列表以相同的顺序包含相同的元素,则它们被定义为相等。
The equals method can be used here and of course ignores the generic types you have declared the two lists to be. The equals method for AbstractList
(which ArrayList and a bunch of other list classes implements) will iterate over both lists and call equals on each of the elements in order, once done it makes sure there aren't any items left in either list.
这里可以使用 equals 方法,当然会忽略您声明两个列表的泛型类型。equals 方法AbstractList
(由 ArrayList 和一堆其他列表类实现)将遍历两个列表并按顺序调用每个元素的 equals,一旦完成,它确保两个列表中都没有任何项目。
Given all this, you will be able to call the equals method to determine weather two lists contain the same elements:
鉴于所有这些,您将能够调用 equals 方法来确定天气两个列表包含相同的元素:
List<Aclass> A1 = new ArrayList<Aclass>();
List<Bclass> b1 = new ArrayList<Bclass>();
// getElement returns a private field that can be cast to both Aclass and Bclass
A1.add(getElement());
b1.add(getElement());
if (A1.equals(b1)) {
System.out.println("two lists are equal");
}