Queue 接口簡介
對于 Queue 接口扶叉,Java的官方文只有這樣一句話:
A
Queue
is a collection for holding elements prior to processing. Besides basicCollection
operations, queues provide additional insertion, removal, and inspection operations.
大概講了兩點:
-
Queue
是用于在處理之前保存元素的集合 -
Queue
提供額外的插入,刪除和檢查操作(相比于Collection
的基本操作)
接著講述了 Queue
接口的一些規(guī)則:(這里和原文檔的順序稍有不同)
Queues typically, but not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to their values. Whatever ordering is used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.
It is possible for a Queue implementation to restrict the number of elements that it holds; such queues are known as bounded. Some Queue implementations in java.util.concurrent are bounded, but the implementations in java.util are not.
這里簡單理解一下就好了:
- 排序規(guī)則:
隊列通常(但不一定)以 FIFO 方式對元素進(jìn)行排序帕膜。優(yōu)先級隊列(priority queues)除外枣氧,它們根據(jù)元素的值對元素進(jìn)行排序 。 - 刪除及添加:
無論使用什么排序垮刹,都是通過remove ()
或poll()
方法刪除頭部元素达吞。
在FIFO隊列中,所有新元素都插入隊列的尾部荒典。其他類型的隊列可能使用不同的放置規(guī)則酪劫。(每個Queue實現(xiàn)都必須指定其排序?qū)傩浴? - 界限:
Queue實現(xiàn)可以限制它所擁有的元素數(shù)量;這樣的隊列被稱為有界种蝶。
java.util.concurrent
中的一些實現(xiàn)是有界的契耿;java.util
中的所有實現(xiàn)均是無界的
Queue 接口相關(guān)操作
Queue 接口相關(guān)操作,文檔中有這樣一段描述:
Each Queue method exists in two forms: (1) one throws an exception if the operation fails, and (2) the other returns a special value if the operation fails (either null or false, depending on the operation).
簡單概述下:
Queue
接口的每個方法有兩種形式:
- 如果操作失敗螃征,拋出異常
- 如果操作失敗搪桂,返回一個特殊的值(
null
或false
)
Type of Operation | Throws exception | Returns special value |
---|---|---|
Insert | add(e) |
offer(e) |
Remove | remove() |
poll() |
Examine | element() |
peek() |
下面是對每個方法的簡單說明:
Insert:在隊列尾部插入元素
add(e)
:超出隊列界限,拋出異常IllegalStateException
offer(e)
:超出隊列界限,返回false
Remove:刪除并返回頭部元素
remove()
:空隊列時踢械,拋出異常NoSuchElementException
poll()
:空隊列時酗电,返回null
Examine:返回頭部元素
element()
:空隊列時,拋出異常NoSuchElementException
peek()
:空隊列時内列,返回null
更多參考:The Queue Interface (The Java? Tutorials > Collections > Interfaces)