【Java隊列】Queue,Deque及其子類使用方法解析

Queue介紹

隊列,先進先出。

Queue接口與List、Set同一級別,都是繼承了Collection接口。
在這裏插入圖片描述

Queue使用

常用方法 解釋
offer(e) 添加元素,成功爲true,失敗爲false
poll () 返回隊列頭,出隊列,隊列空爲null
peek() 返回隊列頭,不出隊列,隊列空爲null

Deque介紹

雙端隊列,可在兩頭入隊和出隊
在這裏插入圖片描述

Deque使用

當成單端隊列使用

常用方法 解釋
offerLast(e) 隊列頭添加元素,成功爲true,失敗爲false
pollFirst () 返回隊列頭,出隊列,隊列空爲null
peekFirst() 返回隊列頭,不出隊列,隊列空爲null

當成雙端隊列使用

常用方法 解釋
offerFirst(e) 隊列頭添加元素,成功爲true,失敗爲false
pollFirst () 返回隊列頭,出隊列,隊列空爲null
peekFirst() 返回隊列頭,不出隊列,隊列空爲null
offerLast(e) 隊列尾添加元素,成功爲true,失敗爲false
pollLast() 返回隊列尾,出隊列,隊列空爲null
peekLast() 返回隊列尾,不出隊列,隊列空爲null

當成棧使用

方法 解釋
push(e) 入棧,失敗則拋出 illegalStateException
peek() 返回棧頂值,失敗拋出NoSuchElementException
pop() 出棧,返回棧頂值,失敗拋出NoSuchElementException

ArrayDeque的介紹

Deque接口的可調整大小的數組實現

  • 沒有容量限制,按需增長
  • 非線程安全
  • 禁止null值
  • 當成棧使用時,比Stack類快
  • 當成單邊隊列使用時,比LinkedList快

底層是一個object數組,初始容量爲8。head和tail屬性控制隊列頭和隊列尾。

transient Object[] elements; // non-private to simplify nested class access
   /**
     * The index of the element at the head of the deque (which is the
     * element that would be removed by remove() or pop()); or an
     * arbitrary number equal to tail if the deque is empty.
     */
    transient int head;

    /**
     * The index at which the next element would be added to the tail
     * of the deque (via addLast(E), add(E), or push(E)).
     */
    transient int tail;

    /**
     * The minimum capacity that we'll use for a newly created deque.
     * Must be a power of 2.
     */
    private static final int MIN_INITIAL_CAPACITY = 8;

在這裏插入圖片描述

ArrayDeque的使用

調用Deque接口中的方法即可

LinkedList的介紹

實現了List和Deque接口的雙端鏈表實現類。接受null值。線程非安全。

在這裏插入圖片描述

核心結構是內部類Node

  private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

LinkedList的使用

調用deque或者List中的接口方法即可使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章