#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指針加一,當數組中沒有數據時,返回nullpublic 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; }