如何为两个对象使用集合方法(removeAll() 和 retainAll()) [英] How to use Collections methods(removeAll() and retainAll()) for two objects
本文介绍了如何为两个对象使用集合方法(removeAll() 和 retainAll())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望结果如下,但实际上没有.即使当我尝试使用 String 而不是 Item Object 时它也有效.我想知道为什么会这样,以及如何编码以获得预期的结果.谢谢.
I expected to result below but actually not. Even though it worked when I tried to use String instead of Item Object. I would like to know why the reasons about that and how to code in order to get expected result.Thanks.
EXPECTED
------------------------------
removed object are:
2
same object are:
1
3
add object are:
4
------------------------------
<小时>
ACTUAL
------------------------------
removed object are:
1
2
3
same object are:
add object are:
1
3
4
------------------------------
<小时>
package com.javastudy;
import java.util.ArrayList;
import java.util.List;
public class CollectionCompareToObjects {
public static void main(String[] args) {
List<Item> before = new ArrayList<Item>();
List<Item> after = new ArrayList<Item>();
before.add(new Item(1L));
before.add(new Item(2L)); // delete
before.add(new Item(3L));
after.add(new Item(1L));
after.add(new Item(3L));
after.add(new Item(4L)); // added
List<Item> removed = new ArrayList<Item>(before);
removed.removeAll(after);
System.out.println("removed objects are:");
for(Item item : removed){
System.out.println(item.getId());
}
List<Item> same = new ArrayList<Item>(before);
same.retainAll(after);
System.out.println("same objects are:");
for(Item item : same){
System.out.println(item.getId());
}
List<Item> added = new ArrayList<Item>(after);
added.removeAll(before);
System.out.println("add objects are:");
for(Item item : added){
System.out.println(item.getId());
}
}
}
package com.javastudy;
public class Item {
Long id;
public Item(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
推荐答案
您尚未实现 equals(),因此您的所有项目都是不同的对象,有些项目恰好具有相同的字段.
You haven't implemented equals() so ALL your Items are different objects some happen to have a field which is the same.
你需要实现equals.
You need to implement equals.
我也建议你使用 long 而不是 Long,除非你想要 id = null.
I also suggest you use long instead of Long, unless you want id = null.
这篇关于如何为两个对象使用集合方法(removeAll() 和 retainAll())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文