我希望比较两个ArrayList的内容。
我是这样存储对象的:
对于ArrayList 1:
Employee e1=new Employee();
e1.setID("1");
e1.setID("2");
ArrayList<Employee>list1 = new ArrayList<Employee>();
if(e1!=null){
list1.add(e1);
}
对于Arraylist 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);
}
}
}
但是我没有得到正确的未匹配列表内容,只有"4"。 我得到的未匹配列表是"1"和"2",这是错误的。 那么我该如何仅获取"unmatchedList"中的未匹配内容呢?
Set
而不是ArrayList
,因为Set
可以轻松进行比较。但是Set
不能存储重复的值。 - svz