美文网首页
Queue/Deque接口

Queue/Deque接口

作者: 言西枣 | 来源:发表于2016-05-18 22:04 被阅读100次

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

    相关文章

      网友评论

          本文标题:Queue/Deque接口

          本文链接:https://www.haomeiwen.com/subject/cpbwrttx.html