Queue/Deque接口

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()|

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容