java中 set接口如何用removeALL()删除所有元素?

2025-03-22 17:55:52
推荐回答(2个)
回答1:

移除 set 中那些包含在指定 collection 中的元素(可选操作)。如果指定的 collection 也是一个 set,则此操作会实际修改此
set,这样其值是两个 set 的一个不对称差集。

指定者:接口 Collection 中的 removeAll参数:c - 包含要从此 set 中移除的元素的 collection
返回:如果此 set 由于调用而发生更改,则返回 true抛出:UnsupportedOperationException
- 如果此 set 不支持 removeAll 操作
ClassCastException -
如果此 set 元素的类与指定的 collection 不兼容(可选)
NullPointerException
- 如果此 set 包含 null 元素并且指定的 collection 不允许 null 元素(可选),或者指定的 collection 为
null

回答2:

public static void main(String[] args){
Set set = new HashSet();
set.add("first");
set.add("second");
for (String s : set) {
System.out.println(s);
}
set.removeAll(set);
for (String s : set) {
System.out.println(s);
}
}