Java 集合 removeAll() 方法

2025年3月24日 | 阅读时间:2 分钟

Java 集合接口的 removeAll() 方法仅移除集合中包含在指定集合内的元素。

语法

参数

在此,参数 'c' 表示要从调用集合中移除元素的集合。

返回值

removeAll() 方法返回一个布尔值,如果集合因调用而发生更改,则返回 'true',否则返回 'false'。

抛出

UnsupportedOperationException - 如果此集合不支持 removeAll 方法。

ClassCastException - 如果此集合中的一个或多个元素的类型与调用集合不兼容。

NullPointerException - 如果此集合为 null 或包含一个或多个 null 元素,并且此集合不允许 null 元素。

示例 1

输出

collection : [1, 2, 3, 4, 5, 6, 7, 8, 9]
List of even numbers : [2, 4, 6, 8]
Odd numbers : [1, 3, 5, 7, 9]

示例 2

输出

Total no : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
 Table of 2 : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

示例 3

输出

Exception in thread "main" java.lang.NullPointerException
	at java.util.concurrent.ConcurrentLinkedQueue.checkNotNull(ConcurrentLinkedQueue.java:920)
	at java.util.concurrent.ConcurrentLinkedQueue.offer(ConcurrentLinkedQueue.java:327)
	at java.util.concurrent.ConcurrentLinkedQueue.add(ConcurrentLinkedQueue.java:297)
	at com.tpointtech.JavaCollectionRemoveAllExample3.main(JavaCollectionRemoveAllExample3.java:13)
下一个主题Java-Collection