#ArrayDequeue
- 内部数组,双向队列,线程不安全,
栈
性能高于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左边