Java Collection add() 方法

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

Java Collection 接口的 add() 方法可以将指定元素插入到此 Collection 中。如果成功将元素插入到指定的 collection 中,则返回布尔值 'true',否则返回 'false'。

语法

参数

'e' 参数表示要添加到 Collection 的元素。

返回

如果指定的元素不为 null 且此 collection 已成功更改,则 add() 方法返回布尔值 'true'。

抛出

add() 方法抛出

UnsupportedOperationException - 如果此 collection 不支持 add 操作

ClassCastException - 如果指定元素的类阻止其添加到此 collection 中。

NullPointerException - 如果指定的元素为 null 且此 collection 不允许 null 元素

IllegalArgumentException - 如果元素的某些属性阻止其添加到此 collection 中

IllegalStateException - 如果由于某些插入限制,目前无法插入元素

示例 1

输出

The elements in Collection : [34, 12, 45]

示例 2

输出

The elements in Collection : [Anurag, Dhruv, Prena, Bajaj]

示例 3

输出

The elements in Collection : [12, null, 0, 5]

示例 4

输出

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.JavaCollectionAddExample4.main(JavaCollectionAddExample4.java:13)

如果此队列中的任何指定元素为 null,它将如上所述抛出 NullPointerException。

下一主题Java Collection