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.add("1");
list1.add("2");
list1.add("3");
list1.add("4");
list1.add("5");
list1.add("6");
List
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
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;
}
注意:remove方法中有一段关键的代码:if (o.equals(it.next())) ,在执行removeAll方法时是通过equals方法来判断集合元素是否相等的,如果集合的元素是对象,并且没有Override equals方法,可能会导致移除失败!
removeAll方法用于从列表中移除指定collection中包含的所有元素。
语法 removeAll(Collection> c)
c:包含从列表中移除元素的collection对象。
该方法返回值为boolean对象,如果List集合对象由于调用removeAll方法而发生更改,则返回true,否则返回false。
简单来讲就是传入一个list,然后就会清空这个list的元素。
List等集合类的removeAll方法,API文档描述如下:
boolean removeAll(Collection> c)
从列表中移除指定 collection 中包含的其所有元素(可选操作)。
用法案例如下:
List
list1.add("1");
list1.add("2");
list1.add("3");
list1.add("4");
list1.add("5");
list1.add("6");
List
list2.add("2");
list2.add("4");
list2.add("6");
list2.add("8");
list1.removeAll(list2); //删除 2 4 6
removeAll的方法实现在下面的类里面:
java.util.AbstractCollection
具体代码为:
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方法具体代码如下:
public boolean remove(Object o) {
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;
}
注意:remove方法中有一段关键的代码:if (o.equals(it.next())) ,在执行removeAll方法时是通过equals方法来判断集合元素是否相等的,如果集合的元素是对象,并且没有Override equals方法,可能会导致移除失败!