// 创建另一个集合
ArrayList<String> other = new ArrayList<>();
other.add("a");
other.add("b");
other.add("d");
System.out.println("ArrayList 2: " + other);
// 前者是否包含后者某个元素
boolean isContains = isContainsOne(one, other);
System.out.println("ArrayList 1: " + one + " ; isContains:" + isContains);
// 使用retainAll运算后
boolean isRetainAll = one.retainAll(other);
System.out.println("ArrayList 1: " + one + " ; isRetainAll:" + isRetainAll);
}
/**
* 前者是否包含后者某个元素
*
* @param oneList 第一个集合
* @param otherList 第二个集合
* @return 是否包含
*/
private static boolean isContainsOne(ArrayList<String> oneList, ArrayList<String> otherList) {
for (String one : otherList) {
boolean contains = oneList.contains(one);
if (contains) {
return true;
}
}
return false;
}
}
运行结果:
ArrayList 1: [a, b, c]
ArrayList 2: [a, b, d]
ArrayList 1: [a, b, c] ; isContains:true
ArrayList 1: [a, b] ; isRetainAll:true
### 3.总结
retainAll 方法:
>
> Retains only the elements in this list that are contained in the specified collection. In other words, removes from this list all of its elements that are not contained in the specified collection.
>
>
>
只保留此列表中包含在指定集合中的元素。换句话说,从该列表中删除指定集合中不包含的所有元素。我看一下源码:
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, 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;
}
实际上就是求`交集`,但是交集的结果放在了第一个集合里,如果后续还要使用第一个集合就会有影响,而且 `retainAll` 的返回值说明的是 `是否删除了元素` 我们可以看下边的两个例子:
ArrayList 1: [a, b, c]
ArrayList 2: [e, f, g]
ArrayList 1: [a, b, c] ; isContains:false
ArrayList 1: [] ; isRetainAll:true
ArrayList 1: [a, b, c]
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!