1. 概述
在本篇教程中,我们来聊聊 Collection
接口中两个看起来功能相似、实则大有不同的方法:clear()
和 removeAll()
。
我们会先看看它们的定义,然后通过简短的示例来实际感受一下两者的差异。
2. Collection.clear()
我们先来看 Collection.clear()
方法。可以查阅 官方 Javadoc 获取详细说明。
✅ 它的作用非常直接:清空集合中的所有元素。
也就是说,无论你调用哪个集合的 clear()
方法,最终这个集合都会变为空。
@Test
void whenClear_thenListBecomesEmpty() {
Collection<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
collection.clear();
assertTrue(collection.isEmpty());
}
这段代码执行后,collection
就变成了一个空集合。简单粗暴!
3. Collection.removeAll()
接着我们来看 removeAll() 的 Javadoc。
⚠️ 它接受一个 Collection
类型参数,并移除当前集合中所有也存在于该参数集合中的元素。
换句话说,它是做“交集删除”的——只删掉那些两个集合共有的元素。
@Test
void whenRemoveAll_thenFirstListMissElementsFromSecondList() {
Collection<Integer> firstCollection = new ArrayList<>(
Arrays.asList(1, 2, 3, 4, 5));
Collection<Integer> secondCollection = new ArrayList<>(
Arrays.asList(3, 4, 5, 6, 7));
firstCollection.removeAll(secondCollection);
assertEquals(
Arrays.asList(1, 2),
firstCollection);
assertEquals(
Arrays.asList(3, 4, 5, 6, 7),
secondCollection);
}
✅ 执行结果符合预期:
- 第一个集合只剩下
[1, 2]
- 第二个集合保持不变
[3, 4, 5, 6, 7]
4. 总结
虽然刚开始看会觉得这两个方法差不多,但其实:
方法 | 行为 |
---|---|
clear() |
❌ 清空整个集合 |
removeAll(Collection<?> c) |
⚠️ 只移除和传入集合中相同的元素 |
所以在使用的时候要踩准点,别搞混了。
一如既往,文中涉及的所有代码都可以在 GitHub 仓库 中找到。