天天看点

ArrayDeque源码分析

ArrayDeque不是线程安全的。 

ArrayDeque不可以存取null元素,因为系统根据某个位置是否为null来判断元素的存在。 

当作为栈使用时,性能比Stack好;当作为队列使用时,性能比LinkedList好。 

1.  两个重要的索引:head和tail 

Java代码  

  1. // 第一个元素的索引  
  2. private transient int head;  
  3. // 下个要添加元素的位置,为末尾元素的索引 + 1  
  4. private transient int tail;  

2.  构造方法 

Java代码  

  1. public ArrayDeque() {  
  2.     elements = (E[]) new Object[16]; // 默认的数组长度大小  
  3. }  
  4. public ArrayDeque(int numElements) {  
  5.     allocateElements(numElements); // 需要的数组长度大小  
  6. }  
  7. public ArrayDeque(Collection<? extends E> c) {  
  8.     allocateElements(c.size()); // 根据集合来分配数组大小  
  9.     addAll(c); // 把集合中元素放到数组中  
  10. }  

3.  分配合适大小的数组 

Java代码  

  1. private void allocateElements(int numElements) {  
  2.     int initialCapacity = MIN_INITIAL_CAPACITY;  
  3.     // 找到大于需要长度的最小的2的幂整数。  
  4.     // Tests "<=" because arrays aren't kept full.  
  5.     if (numElements >= initialCapacity) {  
  6.         initialCapacity = numElements;  
  7.         initialCapacity |= (initialCapacity >>>  1);  
  8.         initialCapacity |= (initialCapacity >>>  2);  
  9.         initialCapacity |= (initialCapacity >>>  4);  
  10.         initialCapacity |= (initialCapacity >>>  8);  
  11.         initialCapacity |= (initialCapacity >>> 16);  
  12.         initialCapacity++;  
  13.         if (initialCapacity < 0)   // Too many elements, must back off  
  14.             initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements  
  15.     }  
  16.     elements = (E[]) new Object[initialCapacity];  
  17. }  

4.  扩容 

Java代码  

  1. // 扩容为原来的2倍。  
  2. private void doubleCapacity() {  
  3.     assert head == tail;  
  4.     int p = head;  
  5.     int n = elements.length;  
  6.     int r = n - p; // number of elements to the right of p  
  7.     int newCapacity = n << 1;  
  8.     if (newCapacity < 0)  
  9.         throw new IllegalStateException("Sorry, deque too big");  
  10.     Object[] a = new Object[newCapacity];  
  11.     // 既然是head和tail已经重合了,说明tail是在head的左边。  
  12.     System.arraycopy(elements, p, a, 0, r); // 拷贝原数组从head位置到结束的数据  
  13.     System.arraycopy(elements, 0, a, r, p); // 拷贝原数组从开始到head的数据  
  14.     elements = (E[])a;  
  15.     head = 0; // 重置head和tail为数据的开始和结束索引  
  16.     tail = n;  
  17. }  
  18. // 拷贝该数组的所有元素到目标数组  
  19. private <T> T[] copyElements(T[] a) {  
  20.     if (head < tail) { // 开始索引大于结束索引,一次拷贝  
  21.         System.arraycopy(elements, head, a, 0, size());  
  22.     } else if (head > tail) { // 开始索引在结束索引的右边,分两段拷贝  
  23.         int headPortionLen = elements.length - head;  
  24.         System.arraycopy(elements, head, a, 0, headPortionLen);  
  25.         System.arraycopy(elements, 0, a, headPortionLen, tail);  
  26.     }  
  27.     return a;  
  28. }  

5.  添加元素 

Java代码  

  1. public void addFirst(E e) {  
  2.     if (e == null)  
  3.         throw new NullPointerException();  
  4.     // 本来可以简单地写成head-1,但如果head为0,减1就变为-1了,和elements.length - 1进行与操作就是为了处理这种情况,这时结果为elements.length - 1。  
  5.     elements[head = (head - 1) & (elements.length - 1)] = e;  
  6.     if (head == tail) // head和tail不可以重叠  
  7.         doubleCapacity();  
  8. }  
  9. public void addLast(E e) {  
  10.     if (e == null)  
  11.         throw new NullPointerException();  
  12.     // tail位置是空的,把元素放到这。  
  13.     elements[tail] = e;  
  14.     // 和head的操作类似,为了处理临界情况 (tail为length - 1时),和length - 1进行与操作,结果为0。  
  15.     if ( (tail = (tail + 1) & (elements.length - 1)) == head)  
  16.         doubleCapacity();  
  17. }  
  18. public boolean offerFirst(E e) {  
  19.     addFirst(e);  
  20.     return true;  
  21. }  
  22. public boolean offerLast(E e) {  
  23.     addLast(e);  
  24.     return true;  
  25. }  

6.  删除元素 

删除首尾元素: 

Java代码  

  1. public E removeFirst() {  
  2.     E x = pollFirst();  
  3.     if (x == null)  
  4.         throw new NoSuchElementException();  
  5.     return x;  
  6. }  
  7. public E removeLast() {  
  8.     E x = pollLast();  
  9.     if (x == null)  
  10.         throw new NoSuchElementException();  
  11.     return x;  
  12. }  
  13. public E pollFirst() {  
  14.     int h = head;  
  15.     E result = elements[h]; // Element is null if deque empty  
  16.     if (result == null)  
  17.         return null;  
  18.     // 表明head位置已为空  
  19.     elements[h] = null;     // Must null out slot  
  20.     head = (h + 1) & (elements.length - 1); // 处理临界情况(当h为elements.length - 1时),与后的结果为0。  
  21.     return result;  
  22. }  
  23. public E pollLast() {  
  24.     int t = (tail - 1) & (elements.length - 1); // 处理临界情况(当tail为0时),与后的结果为elements.length - 1。  
  25.     E result = elements[t];  
  26.     if (result == null)  
  27.         return null;  
  28.     elements[t] = null;  
  29.     tail = t; // tail指向的是下个要添加元素的索引。  
  30.     return result;  
  31. }  

删除指定元素: 

Java代码  

  1. public boolean removeFirstOccurrence(Object o) {  
  2.     if (o == null)  
  3.         return false;  
  4.     int mask = elements.length - 1;  
  5.     int i = head;  
  6.     E x;  
  7.     while ( (x = elements[i]) != null) {  
  8.         if (o.equals(x)) {  
  9.             delete(i);  
  10.             return true;  
  11.         }  
  12.         i = (i + 1) & mask; // 从头到尾遍历  
  13.     }  
  14.     return false;  
  15. }  
  16. public boolean removeLastOccurrence(Object o) {  
  17.     if (o == null)  
  18.         return false;  
  19.     int mask = elements.length - 1;  
  20.     int i = (tail - 1) & mask; // 末尾元素的索引  
  21.     E x;  
  22.     while ( (x = elements[i]) != null) {  
  23.         if (o.equals(x)) {  
  24.             delete(i);  
  25.             return true;  
  26.         }  
  27.         i = (i - 1) & mask; // 从尾到头遍历  
  28.     }  
  29.     return false;  
  30. }  

Java代码  

  1. private void checkInvariants() { // 有效性检查  
  2.     assert elements[tail] == null; // tail位置没有元素  
  3.     assert head == tail ? elements[head] == null :  
  4.         (elements[head] != null &&  
  5.             elements[(tail - 1) & (elements.length - 1)] != null); // 如果head和tail重叠,队列为空;否则head位置有元素,tail-1位置有元素。  
  6.     assert elements[(head - 1) & (elements.length - 1)] == null; // head-1的位置没有元素。  
  7. }  
  8. private boolean delete(int i) {  
  9.     checkInvariants();  
  10.     final E[] elements = this.elements;  
  11.     final int mask = elements.length - 1;  
  12.     final int h = head;  
  13.     final int t = tail;  
  14.     final int front = (i - h) & mask; // i前面的元素个数  
  15.     final int back  = (t - i) & mask; // i后面的元素个数  
  16.     // Invariant: head <= i < tail mod circularity  
  17.     if (front >= ((t - h) & mask)) // i不在head和tail之间  
  18.         throw new ConcurrentModificationException();  
  19.     // Optimize for least element motion  
  20.     if (front < back) { // i的位置靠近head,移动开始的元素,返回false。  
  21.         if (h <= i) {  
  22.             System.arraycopy(elements, h, elements, h + 1, front);  
  23.         } else { // Wrap around  
  24.             System.arraycopy(elements, 0, elements, 1, i);  
  25.             elements[0] = elements[mask]; // 处理边缘元素  
  26.             System.arraycopy(elements, h, elements, h + 1, mask - h);  
  27.         }  
  28.         elements[h] = null;  
  29.         head = (h + 1) & mask; // head位置后移  
  30.         return false;  
  31.     } else { // i的位置靠近tail,移动末尾的元素,返回true。  
  32.         if (i < t) { // Copy the null tail as well  
  33.             System.arraycopy(elements, i + 1, elements, i, back);  
  34.             tail = t - 1;  
  35.         } else { // Wrap around  
  36.             System.arraycopy(elements, i + 1, elements, i, mask - i);  
  37.             elements[mask] = elements[0];  
  38.             System.arraycopy(elements, 1, elements, 0, t);  
  39.             tail = (t - 1) & mask;  
  40.         }  
  41.         return true;  
  42.     }  
  43. }  

示意图: 

ArrayDeque源码分析

7.  获取元素 

Java代码  

  1. public E getFirst() {  
  2.     E x = elements[head];  
  3.     if (x == null)  
  4.         throw new NoSuchElementException();  
  5.     return x;  
  6. }  
  7. public E getLast() {  
  8.     E x = elements[(tail - 1) & (elements.length - 1)]; // 处理临界情况(当tail为0时),与后的结果为elements.length - 1。  
  9.     if (x == null)  
  10.         throw new NoSuchElementException();  
  11.     return x;  
  12. }  
  13. public E peekFirst() {  
  14.     return elements[head]; // elements[head] is null if deque empty  
  15. }  
  16. public E peekLast() {  
  17.     return elements[(tail - 1) & (elements.length - 1)];  
  18. }  

8.  队列操作 

Java代码  

  1. public boolean add(E e) {  
  2.     addLast(e);  
  3.     return true;  
  4. }  
  5. public boolean offer(E e) {  
  6.     return offerLast(e);  
  7. }  
  8. public E remove() {  
  9.     return removeFirst();  
  10. }  
  11. public E poll() {  
  12.     return pollFirst();  
  13. }  
  14. public E element() {  
  15.     return getFirst();  
  16. }  
  17. public E peek() {  
  18.     return peekFirst();  
  19. }  

9.  栈操作 

Java代码  

  1. public void push(E e) {  
  2.     addFirst(e);  
  3. }  
  4. public E pop() {  
  5.     return removeFirst();  
  6. }  

10.  集合方法 

Java代码  

  1. public int size() {  
  2.     return (tail - head) & (elements.length - 1); // 和elements.length - 1进行与操作是为了处理当tail < head时的情况。  
  3. }  
  4. public boolean isEmpty() {  
  5.     return head == tail; // tail位置的元素一定为空,head和tail相等,也为空。  
  6. }  
  7. // 向前迭代器  
  8. public Iterator<E> iterator() {  
  9.     return new DeqIterator();  
  10. }  
  11. // 向后迭代器  
  12. public Iterator<E> descendingIterator() {  
  13.     return new DescendingIterator();  
  14. }  

Java代码  

  1.   private class DeqIterator implements Iterator<E> {  
  2.       private int cursor = head;  
  3.       private int fence = tail; // 迭代终止索引,同时也为了检测并发修改。  
  4.       private int lastRet = -1; // 最近的next()调用返回的索引。据此可以定位到需要删除元素的位置。  
  5.       public boolean hasNext() {  
  6.           return cursor != fence;  
  7.       }  
  8.       public E next() {  
  9.           if (cursor == fence)  
  10.               throw new NoSuchElementException();  
  11.           E result = elements[cursor];  
  12.           // This check doesn't catch all possible comodifications,  
  13.           // but does catch the ones that corrupt traversal  
  14.           if (tail != fence || result == null)  
  15.               throw new ConcurrentModificationException();  
  16.           lastRet = cursor;  
  17.           cursor = (cursor + 1) & (elements.length - 1); // 游标位置加1  
  18.           return result;  
  19.       }  
  20.       public void remove() {  
  21.           if (lastRet < 0)  
  22.               throw new IllegalStateException();  
  23.           if (delete(lastRet)) { // 如果将元素从右往左移,需要将游标减1。  
  24.               cursor = (cursor - 1) & (elements.length - 1); // 游标位置回退1。 
  25. fence = tail; // 重置阀值。  
  26.    }  
  27.           lastRet = -1;  
  28.       }  
  29.   }  

Java代码  

  1. private class DescendingIterator implements Iterator<E> {  
  2.     private int cursor = tail; // 游标开始索引为tail  
  3.     private int fence = head; // 游标的阀值为head  
  4.     private int lastRet = -1;  
  5.     public boolean hasNext() {  
  6.         return cursor != fence;  
  7.     }  
  8.     public E next() {  
  9.         if (cursor == fence)  
  10.             throw new NoSuchElementException();  
  11.         cursor = (cursor - 1) & (elements.length - 1); // tail是下个添加元素的位置,所以要减1才是尾节点的索引。  
  12.         E result = elements[cursor];  
  13.         if (head != fence || result == null)  
  14.             throw new ConcurrentModificationException();  
  15.         lastRet = cursor;  
  16.         return result;  
  17.     }  
  18.     public void remove() {  
  19.         if (lastRet < 0)  
  20.             throw new IllegalStateException();  
  21.         if (!delete(lastRet)) { // 如果从左往右移,需要将游标加1。  
  22.             cursor = (cursor + 1) & (elements.length - 1);  
  23.             fence = head;  
  24.         }  
  25.         lastRet = -1;  
  26.     }  
  27. }  

Java代码  

  1. public boolean contains(Object o) {  
  2.     if (o == null)  
  3.         return false; // ArrayDeque不可以存储null元素  
  4.     int mask = elements.length - 1;  
  5.     int i = head;  
  6.     E x;  
  7.     while ( (x = elements[i]) != null) {  
  8.         if (o.equals(x))  
  9.             return true;  
  10.         i = (i + 1) & mask; // 处理临界情况  
  11.     }  
  12.     return false;  
  13. }  
  14. public boolean remove(Object o) {  
  15.     return removeFirstOccurrence(o);  
  16. }  
  17. public void clear() {  
  18.     int h = head;  
  19.     int t = tail;  
  20.     if (h != t) { // clear all cells  
  21.         head = tail = 0; // 重置首尾索引  
  22.         int i = h;  
  23.         int mask = elements.length - 1;  
  24.         do {  
  25.             elements[i] = null; // 清除元素  
  26.             i = (i + 1) & mask;  
  27.         } while (i != t);  
  28.     }  
  29. }  
  30. public Object[] toArray() {  
  31.     return copyElements(new Object[size()]); // 把所有元素拷贝到新创建的Object数组上,所以对返回数组的修改不会影响该双端队列。  
  32. }  
  33. public <T> T[] toArray(T[] a) {  
  34.     int size = size();  
  35.     if (a.length < size) // 目标数组大小不够  
  36.         a = (T[])java.lang.reflect.Array.newInstance(  
  37.                 a.getClass().getComponentType(), size); // 利用反射创建类型为T,大小为size的数组。  
  38. yElements(a); // 拷贝所有元素到目标数组。  
  39.     if (a.length > size)  
  40.         a[size] = null; // 结束标识  
  41.     return a;  
  42. }  

11.  Object方法 

Java代码  

  1. public ArrayDeque<E> clone() {  
  2.     try {  
  3.         ArrayDeque<E> result = (ArrayDeque<E>) super.clone();  
  4.         result.elements = Arrays.copyOf(elements, elements.length); // 深度复制。  
  5.         return result;  
  6.     } catch (CloneNotSupportedException e) {  
  7.         throw new AssertionError();  
  8.     }  
  9. }