【发布时间】:2012-11-22 09:33:48
【问题描述】:
我想比较两个数组列表的内容。
我以这种方式将对象存储在其中。
对于数组列表 1:
Employee e1=new Employee();
e1.setID("1");
e1.setID("2");
ArrayList<Employee>list1 = new ArrayList<Employee>();
if(e1!=null){
list1.add(e1);
}
对于数组列表 2:
Employee e2=new Employee();
e2.setID("1");
e2.setID("2");
e2.setID("4");
ArrayList<Employee>list2 = new ArrayList<Employee>();
if(e2!=null){
list2.add(e2);
}
现在我正在尝试以这种方式比较上面的arraylist内容
ArrayList<Employee>unmatchedList = new ArrayList<Employee>();
for (Employee l1 : list1){
if(!list2.contains(l1.getID())){
System.out.println("list2 does not contains this ID"+l1.getID());
Employee e3=new Employee();
e3.setID(l1.getID());
if(unmatchedList==null){
unmatchedList=new ArrayList<Employee>();
unmatchedList.add(e3);
}
if(unmatchedList!=null){
unmatchedList.add(e3);
}
}
}
但我没有将正确的 unmatchedList 内容设置为“4”。 我得到 unmatchedList 为“1”和“2”,这是错误的。 那么如何才能仅在“unmatchedList”中获得不匹配的内容
【问题讨论】:
-
您可能希望使用
Set而不是ArrayList。在那里很容易进行比较。虽然Set不会让您存储重复值。 -
请提供Employee类的代码。
-
@svz 诚然,重复的员工听起来有点怪异——或者可能是双胞胎?我的意思是我的雇主很想复制我们,但他从来没有成功过......