Queue.ArrayDequeue

#ArrayDequeuejava

  • 內部數組,雙向隊列,線程不安全,性能高於stack。作隊列性能高於linkedList,內部數組。
  • 內部操做指針,進行操做,容量不足,自動擴容。
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;
  • offer方法和add方法都是經過其中的addLast方法實現,每添加一個元素,就把元素加到數組的尾部,此時,head指針沒有變化,而tail指針加一,由於指針是循環加的,因此當tail追上head,((this.tail = this.tail + 1 & this.elements.length - 1) == this.head)時,數組容量翻一倍,繼續執行。
public void addLast(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[tail] = e;
        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
            doubleCapacity();
    }
  • remove方法和poll方法都是經過其中的pollFirst方法實現,每移除一個元素,該元素所在位置變成null,此時,tail指針沒有變化,而head指針加一,當數組中沒有數據時,返回null
public E pollFirst() {
        int h = head;
        @SuppressWarnings("unchecked")
        E result = (E) elements[h];
        // Element is null if deque empty
        if (result == null)
            return null;
        elements[h] = null;     // Must null out slot
        head = (h + 1) & (elements.length - 1);
        return result;
    }
  • 擴容,先複製head右邊,再複製head左邊
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息