【发布时间】:2019-05-31 06:01:49
【问题描述】:
我对虚拟图的启发式算法有问题,我必须从两个整数列表中计算数字的元素:我必须将第一个的数字和不在其中的数字放入一个列表中第二个列表。
我尝试了两个 addAll 和一个 removeAll(secondList) 并且它可以工作,但是当列表有 duplicates 它不起作用,因为也删除了重复的元素:
//Test lists
List<Integer> ls1 = Arrays.asList(1,1,2,3);
List<Integer> ls3 = Arrays.asList(1,3);
List<Integer> s = new ArrayList<>();
s.addAll(ls1);
System.out.println("Add " + ls1);
s.addAll(ls3);
System.out.println("Add " + ls3);
System.out.println("New list" + s);
s.removeAll(ls3);
System.out.println("Expected value (1,2)");
System.out.println("Result List " + s);
新列表为 [1, 1, 2, 3, 1, 3],预期输出为 [1,2] 但实际输出仅为 2。
【问题讨论】:
-
为什么不迭代列表 ls1 并仅在没有以前的实例时才将元素添加到新列表中?
-
看看
List#retainAll和Set是什么