如何使用Java List等集合类的removeAll方法

2025-03-05 10:33:56
推荐回答(1个)
回答1:

List等集合类的removeAll方法,API文档描述如下:

1
2

boolean removeAll(Collection c)
从列表中移除指定 collection 中包含的其所有元素(可选操作)。

用法案例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

List list1 = new ArrayList();
list1.add("1");
list1.add("2");
list1.add("3");
list1.add("4");
list1.add("5");
list1.add("6");

List list2 = new ArrayList();
list2.add("2");
list2.add("4");
list2.add("6");
list2.add("8");

list1.removeAll(list2); //删除 2 4 6

removeAll的方法实现在下面的类里面:
java.util.AbstractCollection
具体代码为:

1
2
3
4
5
6
7
8
9
10
11

public boolean removeAll(Collection c) {
boolean modified = false;
Iterator it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}

可以看到在调用removeAll方法时,实际上是循环调用了remove方法,remove方法具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

public boolean remove(Object o) {
Iterator it = iterator();
if (o==null) {
while (it.hasNext()) {
if (it.next()==null) {
it.remove();
return true;
}
}
} else {
while (it.hasNext()) {
if (o.equals(it.next())) {
it.remove();
return true;
}
}
}
return false;
}