需要用到List接口中定义的几个方法:
- addAll(Collection<? extends E> c) :按指定集合的Iterator返回的顺序将指定集合中的所有元素追加到此列表的末尾 实例代码:
- retainAll(Collection<?> c): 仅保留此列表中包含在指定集合中的元素。
- removeAll(Collection<?> c) :从此列表中删除指定集合中包含的所有元素。
public class SetMathematics_example {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>();
list1.addAll(Arrays.asList(1,2,3,4));
List<Integer> list2 = new ArrayList<Integer>();
list2.addAll(Arrays.asList(2,3,4,5));
// 并集
// list1.addAll(list2);
// 交集
// list1.retainAll(list2);
// 差集
// list1.removeAll(list2);
// 无重复并集
list2.removeAll(list1);
list1.addAll(list2);
for (Integer i : list1) {
System.out.print(i+ " ");
}
}
}