//用數組存儲元素
transient Object[] elements; // non-private to simplify nested class access
//頭部元素的索引
transient int head;
//尾部下一個将要被加入的元素的索引
transient int tail;
//最小容量,必須為2的幂次方
private static final int MIN_INITIAL_CAPACITY = 8;
在 ArrayDeque 底部是使用數組存儲元素,同時還使用了兩個索引來表征目前數組的狀态,分别是 head 和 tail。head 是頭部元素的索引,但注意 tail 不是尾部元素的索引,而是尾部元素的下一位,即下一個将要被加入的元素的索引。
public ArrayDeque() {
elements = new Object[16];
}
public ArrayDeque(int numElements) {
allocateElements(numElements);
}
public ArrayDeque(Collection<? extends E> c) {
allocateElements(c.size());
addAll(c);
}
ArrayDeque 對數組的大小(即隊列的容量)有特殊的要求,必須是 2^n。通過
allocateElements
方法計算初始容量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
// Find the best power of two to hold elements.
// Tests "<=" because arrays aren't kept full.
if (numElements >= initialCapacity) {
initialCapacity = numElements;
initialCapacity |= (initialCapacity >>> 1);
initialCapacity |= (initialCapacity >>> 2);
initialCapacity |= (initialCapacity >>> 4);
initialCapacity |= (initialCapacity >>> 8);
initialCapacity |= (initialCapacity >>> 16);
initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off
initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
}
elements = new Object[initialCapacity];
}
private void doubleCapacity() {
assert head == tail; //擴容時頭部索引和尾部索引肯定相等
int p = head;
int n = elements.length;
//頭部索引到數組末端(length-1處)共有多少元素
int r = n - p; // number of elements to the right of p
//容量翻倍
int newCapacity = n << 1;
//容量過大,溢出了
if (newCapacity < 0)
throw new IllegalStateException("Sorry, deque too big");
//配置設定新空間
Object[] a = new Object[newCapacity];
//複制頭部索引到數組末端的元素到新數組的頭部
System.arraycopy(elements, p, a, 0, r);
//複制其餘元素
System.arraycopy(elements, 0, a, r, p);
elements = a;
//重置頭尾索引
head = 0;
tail = n;
}
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;
}
public E pollLast() {
int t = (tail - 1) & (elements.length - 1);
@SuppressWarnings("unchecked")
E result = (E) elements[t];
if (result == null)
return null;
elements[t] = null;
tail = t;
return result;
}
擷取隊頭和隊尾的元素
1
2
3
4
5
6
7
8
9
10
@SuppressWarnings("unchecked")
public E peekFirst() {
// elements[head] is null if deque empty
return (E) elements[head];
}
@SuppressWarnings("unchecked")
public E peekLast() {
return (E) elements[(tail - 1) & (elements.length - 1)];
}
疊代器
ArrayDeque 在疊代是檢查并發修改并沒有使用類似于 ArrayList 等容器中使用的 modCount,而是通過尾部索引的來确定的。具體參考 next 方法中的注釋。但是這樣不一定能保證檢測到所有的并發修改情況,加入先移除了尾部元素,又添加了一個尾部元素,這種情況下疊代器是沒法檢測出來的。
private class DeqIterator implements Iterator<E> {
/**
* Index of element to be returned by subsequent call to next.
*/
private int cursor = head;
/**
* Tail recorded at construction (also in remove), to stop
* iterator and also to check for comodification.
*/
private int fence = tail;
/**
* Index of element returned by most recent call to next.
* Reset to -1 if element is deleted by a call to remove.
*/
private int lastRet = -1;
public boolean hasNext() {
return cursor != fence;
}
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
@SuppressWarnings("unchecked")
E result = (E) elements[cursor];
// This check doesn't catch all possible comodifications,
// but does catch the ones that corrupt traversal
// 如果移除了尾部元素,會導緻tail != fence
// 如果移除了頭部元素,會導緻 result == null
if (tail != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
cursor = (cursor + 1) & (elements.length - 1);
return result;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (delete(lastRet)) { // if left-shifted, undo increment in next()
cursor = (cursor - 1) & (elements.length - 1);
fence = tail;
}
lastRet = -1;
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
Object[] a = elements;
int m = a.length - 1, f = fence, i = cursor;
cursor = f;
while (i != f) {
@SuppressWarnings("unchecked") E e = (E)a[i];
i = (i + 1) & m;
if (e == null)
throw new ConcurrentModificationException();
action.accept(e);
}
}
}