标签:修改 ack int log string rem copy retain print
package com.example; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ListOpt { private List intersect(List ls1, List ls2) { List list = new ArrayList(Arrays.asList(new Object[ls1.size()])); Collections.copy(list, ls1); list.retainAll(ls2); return list; } private List union(List ls1, List ls2) { List list = new ArrayList(Arrays.asList(new Object[ls1.size()])); Collections.copy(list, ls1); list.addAll(ls2); return list; } private List diff(List ls1, List ls2) { List list = new ArrayList(Arrays.asList(new Object[ls1.size()])); Collections.copy(list, ls1); list.removeAll(ls2); return list; } public static void main(String[] args) { List<Integer> l1 = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; List<Integer> l2 = new ArrayList<Integer>() {{ add(2); add(3); add(4); }}; ListOpt opt = new ListOpt(); List intersectList = opt.intersect(l1, l2); List union = opt.union(l1, l2); List diff = opt.diff(l1, l2); print(intersectList); print(union); print(diff); } private static void print(List lst) { if (lst.size() == 0) { return; } for (int i = 0; i <lst.size(); ++i) { System.out.println(lst.get(i)); } System.out.println("---"); } }
2 3 --- 1 2 3 2 3 4 --- 1 ---
在操作之前对原对象进行了拷贝,如果对原对象直接操作会修改原来的对象
标签:修改 ack int log string rem copy retain print
原文地址:http://www.cnblogs.com/kaituorensheng/p/7226085.html