Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. Null elements are pro
| 57 | * @param <E> the type of elements held in this collection |
| 58 | */ |
| 59 | public class ArrayDeque<E> extends AbstractCollection<E> |
| 60 | implements Deque<E>, Cloneable, java.io.Serializable |
| 61 | { |
| 62 | /** |
| 63 | * The array in which the elements of the deque are stored. |
| 64 | * The capacity of the deque is the length of this array, which is |
| 65 | * always a power of two. The array is never allowed to become |
| 66 | * full, except transiently within an addX method where it is |
| 67 | * resized (see doubleCapacity) immediately upon becoming full, |
| 68 | * thus avoiding head and tail wrapping around to equal each |
| 69 | * other. We also guarantee that all array cells not holding |
| 70 | * deque elements are always null. |
| 71 | */ |
| 72 | private transient Object[] elements; |
| 73 | |
| 74 | /** |
| 75 | * The index of the element at the head of the deque (which is the |
| 76 | * element that would be removed by remove() or pop()); or an |
| 77 | * arbitrary number equal to tail if the deque is empty. |
| 78 | */ |
| 79 | private transient int head; |
| 80 | |
| 81 | /** |
| 82 | * The index at which the next element would be added to the tail |
| 83 | * of the deque (via addLast(E), add(E), or push(E)). |
| 84 | */ |
| 85 | private transient int tail; |
| 86 | |
| 87 | /** |
| 88 | * The minimum capacity that we'll use for a newly created deque. |
| 89 | * Must be a power of 2. |
| 90 | */ |
| 91 | private static final int MIN_INITIAL_CAPACITY = 8; |
| 92 | |
| 93 | // ****** Array allocation and resizing utilities ****** |
| 94 | |
| 95 | /** |
| 96 | * Allocate empty array to hold the given number of elements. |
| 97 | * |
| 98 | * @param numElements the number of elements to hold |
| 99 | */ |
| 100 | private void allocateElements(int numElements) { |
| 101 | int initialCapacity = MIN_INITIAL_CAPACITY; |
| 102 | // Find the best power of two to hold elements. |
| 103 | // Tests "<=" because arrays aren't kept full. |
| 104 | if (numElements >= initialCapacity) { |
| 105 | initialCapacity = numElements; |
| 106 | initialCapacity |= (initialCapacity >>> 1); |
| 107 | initialCapacity |= (initialCapacity >>> 2); |
| 108 | initialCapacity |= (initialCapacity >>> 4); |
| 109 | initialCapacity |= (initialCapacity >>> 8); |
| 110 | initialCapacity |= (initialCapacity >>> 16); |
| 111 | initialCapacity++; |
| 112 | |
| 113 | if (initialCapacity < 0) // Too many elements, must back off |
| 114 | initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements |
| 115 | } |
| 116 | elements = new Object[initialCapacity]; |
nothing calls this directly
no outgoing calls
no test coverage detected