ArrayDeque简介
JDK源码文档描述特点如下:
- 动态扩展的循环数组实现的双端队列
- 线程不安全
- 不允许Null元素
- 用于栈比Stack快,用于队列比LinkedList快
- 大部分操作均摊时间复杂度为O(1),除了remove, removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, 复杂度为O(n)
作为双端队列使用:
Deque<Integer> deque=new ArrayDeque<>();
deque.offerLast(1);//尾部加入
deque.offerFirst(2);//头部加入
deque.size();//队列大小
deque.peekFirst();//检查队头
deque.peekLast();//检查队尾
deque.pollFirst();//队头出队
deque.pollLast();//队尾出队
作为普通队列使用:
Queue<Integer> queue=new ArrayDeque<>();
queue.offer(1);//尾部加入
queue.size();//队列大小
queue.peek();//检查队头
queue.poll();//队头出队
作为栈使用:
ArrayDeque<Integer> stack=new ArrayDeque<>();//JDK中没有stack接口
stack.push(1);//入栈
stack.size();//栈深度
stack.peek();//检查栈顶
stack.poll();//出栈
ArrayDeque实现原理
ArrayDeque内部是一个可扩容的循环数组。循环数组使用头尾两个指针,使得物理上的普通数组变为逻辑上循环的数组。
ArrayDeque中用以下三个实例变量表示:
transient Object[] elements;
transient int head;
transient int tail;
循环数组的特点:
- 如果head=tail:数组为空,长度为0;
- 如果head<tail:第一个元素为elements[head],最后一个元素为elements[tail-1],长度为tail-head
- 如果head>tail,且tail=0:第一个元素为elements[head],最后一个元素为elements[elements.length-1],长度为elements.length-head
- 如果head>tail>0:形成循环。第一个元素为elements[head],最后一个元素为elements[tail-1],元素索引从head到elements.length-1,再从0到tail-1
构造方法
默认构造函数,会创建长度为16的数组:
public ArrayDeque() {
elements = new Object[16];
}
带初始容量的构造函数,会计算最合适的数组长度:
public ArrayDeque(int numElements) {
allocateElements(numElements);
}
private void allocateElements(int numElements) {
elements = new Object[calculateSize(numElements)];
}
为了使用与运算代替求余,会保证长度为2的n次幂。calculateSize方法的核心就是计算严格大于numElements的2的n次幂数。注意是“严格大于”,因为循环数组必须至少有一个空位置。
private static int calculateSize(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
}
return initialCapacity;
}
尾部添加
从尾部添加,核心是找到添加位置,用与运算最方便:(tail + 1) & (elements.length - 1))
public void addLast(E e) {
if (e == null)
throw new NullPointerException();
elements[tail] = e;
if ( (tail = (tail + 1) & (elements.length - 1)) == head)
doubleCapacity();
}
如果尾部添加的位置和head重合了,表示数组要满了,必须扩容。扩容大小很简单,两倍。关键是如何“整理元素”,把元素移到新数组的左端。
private void doubleCapacity() {
assert head == tail;//扩容前置条件一定是这个
int p = head;
int n = elements.length;
int r = n - p; // head右边元素(含head本身)的个数,这些元素要先移到新数组左边
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);//先复制 head右边元素(含head本身)
System.arraycopy(elements, 0, a, r, p);//再复制head左边元素
elements = a;
head = 0;
tail = n;
}
头部添加
关键也是添加的位置:(head - 1) & (elements.length - 1)
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
头部删除
头部删除的关键是调整头指针head,方法也类似:head = (h + 1) & (elements.length - 1)。还有一点值得注意,elements[h] = 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;
}
尾部删除
尾部删除也类似,元素位置是:(tail - 1) & (elements.length - 1)。
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;
}
队列长度
循环数组长度计算公式:(tail - head) & (elements.length - 1)
public int size() {
return (tail - head) & (elements.length - 1);
}