Queue
- 先入先出(FIFO)的数据结构
boolean add(E element)
boolean offer(E element)
在队列尾部添加元素,如果队列已满,add将抛出IllegalStateException
,offer返回false
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
E remove()
E poll()
删除并返回队头元素,如果队空,remove抛出NoSuchElementException
, poll返回null
public E remove() {
E x = poll();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
E element()
E peek()
返回队头元素,如果队空,element抛出NoSuchElementException
, peek返回null
public E element() {
E x = peek();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
上面三段代码来自jdk1.8 java.util.AbstractQueue
Deque
- 双端队列,只能在队列的首尾进行操作
- 实现类:ArrayDeque, ConcurrentLinkedDeque, LinkedBlockingDeque, LinkedList
- Deque被推荐用来取代Stack类
Summary of Deque methods
||First Element (Head)||Last Element (Tail)||
|-|
||Throws exception|Special value|Throws exception|Special value|
|Insert|addFirst(e)|offerFirst(e)|addLast(e)|offerLast(e)|
|Remove|removeFirst()|pollFirst()|removeLast()|pollLast()|
|Examine|getFirst()|peekFirst()|getLast()|peekLast()|