浏览一下ArrayDeque的一些源码(常用方法):
public class ArrayDeque extends AbstractCollection implements Deque,
Cloneable, Serializable {
transient Object[] elements; // non-private to simplify nested class access
transient int head;
transient int tail;
private static final int MIN_INITIAL_CAPACITY = 8;
private void allocateElements(int numElements) {
int initialCapacity = MIN_INITIAL_CAPACITY;
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];
}
/**
* Doubles the capacity of this deque. Call only when full, i.e., when head
* and tail have wrapped around to become equal.
*/
private void doubleCapacity() {
assert head == tail;
int p = head;
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;
head = 0;
tail = n;
}
/**
* 构造一个初始容量能够容纳 16 个元素的空数组双端队列。
*/
public ArrayDeque() {
elements = new Object[16];
}
/**
* 构造一个初始容量能够容纳指定数量的元素的空数组双端队列。
*
* @param numElements
*/
public ArrayDeque(int numElements) {
allocateElements(numElements);
}
/**
* 构造一个包含指定 collection 的元素的双端队列,这些元素按 collection 的迭代器返回的顺序排列。
*
* @param c
*/
public ArrayDeque(Collection c) {
allocateElements(c.size());
addAll(c);
}
/**
* 将指定元素插入此双端队列的开头。
*
* @param e
*/
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
/**
* 将指定元素插入此双端队列的末尾。
*
* @param e
*/
public void addLast(E e) {
if (e == null)
throw new NullPointerException();
elements[tail] = e;
if ((tail = (tail + 1) & (elements.length - 1)) == head)
doubleCapacity();
}
/**
* 将指定元素插入此双端队列的开头。
*
* @param e
* @return
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* 将指定元素插入此双端队列的末尾。
*
* @param e
* @return
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
/**
* 获取并移除此双端队列第一个元素。
*
* @return
*/
public E removeFirst() {
E x = pollFirst();
if (x == null)
throw new NoSuchElementException();
return x;
}
/**
* 获取并移除此双端队列的最后一个元素。
*
* @return
*/
public E removeLast() {
E x = pollLast();
if (x == null)
throw new NoSuchElementException();
return x;
}
/**
* 获取并移除此双端队列的第一个元素;如果此双端队列为空,则返回 null。
*
* @return
*/
public E pollFirst() {
final Object[] elements = this.elements;
final int h = head;
@SuppressWarnings("unchecked")
E result = (E) elements[h];
// Element is null if deque empty
if (result != null) {
elements[h] = null; // Must null out slot
head = (h + 1) & (elements.length - 1);
}
return result;
}
/**
* 获取并移除此双端队列的最后一个元素;如果此双端队列为空,则返回 null。
*
* @return
*/
public E pollLast() {
final Object[] elements = this.elements;
final int t = (tail - 1) & (elements.length - 1);
@SuppressWarnings("unchecked")
E result = (E) elements[t];
if (result != null) {
elements[t] = null;
tail = t;
}
return result;
}
/**
* 获取,但不移除此双端队列的第一个元素。
*
* @return
*/
public E getFirst() {
@SuppressWarnings("unchecked")
E result = (E) elements[head];
if (result == null)
throw new NoSuchElementException();
return result;
}
/**
* 获取,但不移除此双端队列的最后一个元素。
*
* @return
*/
public E getLast() {
@SuppressWarnings("unchecked")
E result = (E) elements[(tail - 1) & (elements.length - 1)];
if (result == null)
throw new NoSuchElementException();
return result;
}
/**
* 获取,但不移除此双端队列的第一个元素;如果此双端队列为空,则返回 null。
*
* @return
*/
@SuppressWarnings("unchecked")
public E peekFirst() {
// elements[head] is null if deque empty
return (E) elements[head];
}
/**
* 获取,但不移除此双端队列的最后一个元素;如果此双端队列为空,则返回 null。
*
* @return
*/
@SuppressWarnings("unchecked")
public E peekLast() {
return (E) elements[(tail - 1) & (elements.length - 1)];
}
/**
* 移除此双端队列中第一次出现的指定元素(当从头部到尾部遍历双端队列时)。
*
* @param o
* @return
*/
public boolean removeFirstOccurrence(Object o) {
if (o != null) {
int mask = elements.length - 1;
int i = head;
for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
if (o.equals(x)) {
delete(i);
return true;
}
}
}
return false;
}
/**
* 移除此双端队列中最后一次出现的指定元素(当从头部到尾部遍历双端队列时)。
*
* @param o
* @return
*/
public boolean removeLastOccurrence(Object o) {
if (o != null) {
int mask = elements.length - 1;
int i = (tail - 1) & mask;
for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
if (o.equals(x)) {
delete(i);
return true;
}
}
}
return false;
}
/**
* 将指定元素插入此双端队列的末尾。
*
* @param e
* @return
*/
public boolean add(E e) {
addLast(e);
return true;
}
/**
* 将指定元素插入此双端队列的末尾。
*
* @param e
* @return
*/
public boolean offer(E e) {
return offerLast(e);
}
/**
* 获取并移除此双端队列所表示的队列的头。
*
* @return
*/
public E remove() {
return removeFirst();
}
/**
* 获取并移除此双端队列所表示的队列的头(换句话说,此双端队列的第一个元素);如果此双端队列为空,则返回 null。
*
* @return
*/
public E poll() {
return pollFirst();
}
/**
* 获取,但不移除此双端队列所表示的队列的头。
*
* @return
*/
public E element() {
return getFirst();
}
/**
* 获取,但不移除此双端队列所表示的队列的头;如果此双端队列为空,则返回 null。
*
* @return
*/
public E peek() {
return peekFirst();
}
/**
* 将元素推入此双端队列所表示的堆栈。
*
* @param e
*/
public void push(E e) {
addFirst(e);
}
/**
* 从此双端队列所表示的堆栈中弹出一个元素。
*
* @return
*/
public E pop() {
return removeFirst();
}
private void checkInvariants() {
assert elements[tail] == null;
assert head == tail ? elements[head] == null
: (elements[head] != null && elements[(tail - 1)
& (elements.length - 1)] != null);
assert elements[(head - 1) & (elements.length - 1)] == null;
}
boolean delete(int i) {
checkInvariants();
final Object[] elements = this.elements;
final int mask = elements.length - 1;
final int h = head;
final int t = tail;
final int front = (i - h) & mask;
final int back = (t - i) & mask;
// Invariant: head <= i < tail mod circularity
if (front >= ((t - h) & mask))
throw new ConcurrentModificationException();
// Optimize for least element motion
if (front < back) {
if (h <= i) {
System.arraycopy(elements, h, elements, h + 1, front);
} else { // Wrap around
System.arraycopy(elements, 0, elements, 1, i);
elements[0] = elements[mask];
System.arraycopy(elements, h, elements, h + 1, mask - h);
}
elements[h] = null;
head = (h + 1) & mask;
return false;
} else {
if (i < t) { // Copy the null tail as well
System.arraycopy(elements, i + 1, elements, i, back);
tail = t - 1;
} else { // Wrap around
System.arraycopy(elements, i + 1, elements, i, mask - i);
elements[mask] = elements[0];
System.arraycopy(elements, 1, elements, 0, t);
tail = (t - 1) & mask;
}
return true;
}
}
/**
* 返回此双端队列中的元素数。
*
* @return
*/
public int size() {
return (tail - head) & (elements.length - 1);
}
/**
* 如果此双端队列未包含任何元素,则返回 true。
*
* @return
*/
public boolean isEmpty() {
return head == tail;
}
/**
* 返回在此双端队列的元素上进行迭代的迭代器。
*
* @return
*/
public Iterator iterator() {
return new DeqIterator();
}
/**
* 返回以逆向顺序在此双端队列的元素上进行迭代的迭代器。
*
* @return
*/
public Iterator descendingIterator() {
return new DescendingIterator();
}
private class DeqIterator implements Iterator {
private int cursor = head;
private int fence = tail;
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
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;
}
@Override
public void forEachRemaining(Consumer 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;
// Android-note: This uses a different heuristic for detecting
// concurrent modification exceptions than next(). As such, this
// is a less
// precise test.
if (e == null)
throw new ConcurrentModificationException();
action.accept(e);
}
}
}
private class DescendingIterator implements Iterator {
private int cursor = tail;
private int fence = head;
private int lastRet = -1;
public boolean hasNext() {
return cursor != fence;
}
public E next() {
if (cursor == fence)
throw new NoSuchElementException();
cursor = (cursor - 1) & (elements.length - 1);
@SuppressWarnings("unchecked")
E result = (E) elements[cursor];
if (head != fence || result == null)
throw new ConcurrentModificationException();
lastRet = cursor;
return result;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (!delete(lastRet)) {
cursor = (cursor + 1) & (elements.length - 1);
fence = head;
}
lastRet = -1;
}
}
/**
* 如果此双端队列包含指定元素,则返回 true。
*
* @param o
* @return
*/
public boolean contains(Object o) {
if (o != null) {
int mask = elements.length - 1;
int i = head;
for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
if (o.equals(x))
return true;
}
}
return false;
}
/**
* 从此双端队列中移除指定元素的单个实例。
*
* @param o
* @return
*/
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
/**
* 从此双端队列中移除所有元素。
*/
public void clear() {
int h = head;
int t = tail;
if (h != t) { // clear all cells
head = tail = 0;
int i = h;
int mask = elements.length - 1;
do {
elements[i] = null;
i = (i + 1) & mask;
} while (i != t);
}
}
/**
* 返回一个以恰当顺序包含此双端队列所有元素的数组(从第一个元素到最后一个元素)。
*
* @return
*/
public Object[] toArray() {
final int head = this.head;
final int tail = this.tail;
boolean wrap = (tail < head);
int end = wrap ? tail + elements.length : tail;
Object[] a = Arrays.copyOfRange(elements, head, end);
if (wrap)
System.arraycopy(elements, 0, a, elements.length - head, tail);
return a;
}
/**
* 返回一个以恰当顺序包含此双端队列所有元素的数组(从第一个元素到最后一个元素);返回数组的运行时类型是指定数组的运行时类型。
*
* @param a
* @return
*/
@SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
final int head = this.head;
final int tail = this.tail;
boolean wrap = (tail < head);
int size = (tail - head) + (wrap ? elements.length : 0);
int firstLeg = size - (wrap ? tail : 0);
int len = a.length;
if (size > len) {
a = (T[]) Arrays.copyOfRange(elements, head, head + size,
a.getClass());
} else {
System.arraycopy(elements, head, a, 0, firstLeg);
if (size < len)
a[size] = null;
}
if (wrap)
System.arraycopy(elements, 0, a, firstLeg, tail);
return a;
}
/**
* 返回此双端队列的副本。
*
* @return
*/
public ArrayDeque clone() {
try {
@SuppressWarnings("unchecked")
ArrayDeque result = (ArrayDeque) super.clone();
result.elements = Arrays.copyOf(elements, elements.length);
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
private static final long serialVersionUID = 2340985798034038923L;
}