腾讯云授权服务中心
五万用户的选择,您身边的云计算顾问
发布日:2021-11-22 14:40 阅读数:
list1.removeAll(list2);查看ArrayList的removeAll的源码,他调用的batchRemove(),
public boolean removeAll(Collection c) { Objects.requireNonNull(c); return batchRemove(c, false); }再看batchRemove的源码,如果传的第二个参数是false,保留差集,如果传的是true,保留的是交集,设计很精妙,
private boolean batchRemove(Collection c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; }因此,removeAll(list2)默认调用false,将不包含的元素进行存储,实现了差集功能,
if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r];
public static void test(List list1, List list2) { list1.addAll(list2); System.out.println(list1); }
public boolean addAll(Collection c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; }
public static void test1(List list1, List list2) { list1.removeAll(list2); list1.addAll(list2); System.out.println(list1); }3. 求交集
public static void test2(List list1, List list2) { list1.retainAll(list2); System.out.println(list1); }我们看retainAll()的源码,他其实调用的,就是这个batchRemove()函数,但是第二个参数,给的是true,所以这两种操作,都可以实现交集,
public boolean retainAll(Collection c) { Objects.requireNonNull(c); return batchRemove(c, true); }
编辑:航网科技 来源:腾讯云
本文版权归原作者所有 转载请注明出处
Copyright © 2011-2020 www.hangw.com. All Rights Reserved 深圳航网科技有限公司 版权所有 增值电信业务经营许可证:粤B2-20201122 - 粤ICP备14085080号
微信扫一扫咨询客服
全国免费服务热线
0755-36300002