# ArrayDeque源码分析

## 引言

### 成员变量:

``````transient Object[] elements; // 数据载体，长度始终为2的幂
transient int tail;//尾指针
``````

1. 这个队列不允许元素为空；
2. 数组至少有一个位置是空的；

[head : elements.length()-1] + [0, tail-1]
队列为空，也就是没有存放任何元素

### 两个构造方法：

``````public ArrayDeque() {
elements = new Object[16];
}
public ArrayDeque(int numElements) {
allocateElements(numElements);
}
``````

``````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];
}
``````

........

### 两个添加方法：

``````public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
doubleCapacity();
}
if (e == null)
throw new NullPointerException();
elements[tail] = e;
if ( (tail = (tail + 1) & (elements.length - 1)) == head)
doubleCapacity();
}
``````

``````private void doubleCapacity() {
int n = elements.length;
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;
tail = n;
}
``````

1. 先做各种合法性校验；
2. 申请新数组（长度扩大一倍）；
4. 保持元素原来顺序拷贝到新数组里；
5. 重置头尾指针。

1. a == -1:
a & (mod-1) == mod - 1;
2. 0 <= a < mod:
a & (mod - 1) == a;
3. a == mod:
a & (mod - 1) == 0

### 两个取首/尾元素并删除的方法：

``````   public E pollFirst() {
@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. removeFirst/LastOccurrence(Object o)方法：
``````  public boolean removeFirstOccurrence(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
Object x;
while ( (x = elements[i]) != null) {
if (o.equals(x)) {
delete(i);
return true;
}
i = (i + 1) & mask;
}
return false;
}

public boolean removeLastOccurrence(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = (tail - 1) & mask;
Object x;
while ( (x = elements[i]) != null) {
if (o.equals(x)) {
delete(i);
return true;
}
i = (i - 1) & mask;
}
return false;
}
``````

ArrayDeque里还有一些比如Iterator（比较简单），Spliterator（没用过）的代码，这边就不分析了。