Java ConcurrentLinkedQueue add() 方法

2024年10月21日 | 2 分钟阅读

ConcurrentLinkedQueue 类的 add() 方法将指定的元素插入此 ConcurrentLinkedQueue 的尾部。 addAll() 方法覆盖了 AbstractQueue<E> 类中的 addAll。

语法

参数

e - 要添加的元素

指定者:

ConcurrentLinkedQueue 类的 add() 方法由以下内容指定:

  1. 接口 Queue<E> 中的 add() 方法。
  2. 接口 Collection<E> 中的 add() 方法。

返回值

add() 方法返回一个布尔值 true。

抛出

NullPointerException:如果指定的元素 e 为 null。

示例 1

输出

After adding 1 to the queue :
[1]
After adding 2 to the queue :
[1, 2]
After adding 3 to the queue :
[1, 2, 3]
After adding 4 to the queue :
[1, 2, 3, 4]
After adding 5 to the queue :
[1, 2, 3, 4, 5]

示例 2

输出

Queue :
718
8
18
119
Max number = 718
Min number = 8

示例 3

输出

1. Name = Reema
2. Name = Jyoti
3. Name = Rahul
4. Name = Anushtha

示例 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.javaTpoint.ConcurrentLinkedQueueAddExample4.main(ConcurrentLinkedQueueAddExample4.java:7)

如果此队列中任何指定的元素为 null,则会引发如上所述的 NullPointerException。