ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
(Generate patch)

Comparing jsr166/src/main/java/util/ArrayDeque.java (file contents):
Revision 1.3 by dl, Tue Mar 8 17:52:02 2005 UTC vs.
Revision 1.77 by jsr166, Tue Oct 18 00:33:05 2016 UTC

# Line 1 | Line 1
1   /*
2   * Written by Josh Bloch of Google Inc. and released to the public domain,
3 < * as explained at http://creativecommons.org/licenses/publicdomain.
3 > * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
4   */
5  
6   package java.util;
7 < import java.io.*;
7 >
8 > import java.io.Serializable;
9 > import java.util.function.Consumer;
10 > import java.util.function.Predicate;
11 > import java.util.function.UnaryOperator;
12  
13   /**
14   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 15 | Line 19 | import java.io.*;
19   * {@link Stack} when used as a stack, and faster than {@link LinkedList}
20   * when used as a queue.
21   *
22 < * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
23 < * Exceptions include {@link #remove(Object) remove}, {@link
24 < * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
25 < * removeLastOccurrence}, {@link #contains contains }, {@link #iterator
26 < * iterator.remove()}, and the bulk operations, all of which run in linear
27 < * time.
22 > * <p>Most {@code ArrayDeque} operations run in amortized constant time.
23 > * Exceptions include
24 > * {@link #remove(Object) remove},
25 > * {@link #removeFirstOccurrence removeFirstOccurrence},
26 > * {@link #removeLastOccurrence removeLastOccurrence},
27 > * {@link #contains contains},
28 > * {@link #iterator iterator.remove()},
29 > * and the bulk operations, all of which run in linear time.
30   *
31 < * <p>The iterators returned by this class's <tt>iterator</tt> method are
32 < * <i>fail-fast</i>: If the deque is modified at any time after the iterator
33 < * is created, in any way except through the iterator's own remove method, the
34 < * iterator will generally throw a {@link ConcurrentModificationException}.
35 < * Thus, in the face of concurrent modification, the iterator fails quickly
36 < * and cleanly, rather than risking arbitrary, non-deterministic behavior at
37 < * an undetermined time in the future.
31 > * <p>The iterators returned by this class's {@link #iterator() iterator}
32 > * method are <em>fail-fast</em>: If the deque is modified at any time after
33 > * the iterator is created, in any way except through the iterator's own
34 > * {@code remove} method, the iterator will generally throw a {@link
35 > * ConcurrentModificationException}.  Thus, in the face of concurrent
36 > * modification, the iterator fails quickly and cleanly, rather than risking
37 > * arbitrary, non-deterministic behavior at an undetermined time in the
38 > * future.
39   *
40   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
41   * as it is, generally speaking, impossible to make any hard guarantees in the
42   * presence of unsynchronized concurrent modification.  Fail-fast iterators
43 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
43 > * throw {@code ConcurrentModificationException} on a best-effort basis.
44   * Therefore, it would be wrong to write a program that depended on this
45   * exception for its correctness: <i>the fail-fast behavior of iterators
46   * should be used only to detect bugs.</i>
47   *
48   * <p>This class and its iterator implement all of the
49 < * optional methods of the {@link Collection} and {@link
50 < * Iterator} interfaces.  This class is a member of the <a
51 < * href="{@docRoot}/../guide/collections/index.html"> Java Collections
52 < * Framework</a>.
49 > * <em>optional</em> methods of the {@link Collection} and {@link
50 > * Iterator} interfaces.
51 > *
52 > * <p>This class is a member of the
53 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
54 > * Java Collections Framework</a>.
55   *
56   * @author  Josh Bloch and Doug Lea
57 + * @param <E> the type of elements held in this deque
58   * @since   1.6
49 * @param <E> the type of elements held in this collection
59   */
60   public class ArrayDeque<E> extends AbstractCollection<E>
61                             implements Deque<E>, Cloneable, Serializable
62   {
63      /**
64 <     * The array in which the elements of in the deque are stored.
65 <     * The capacity of the deque is the length of this array, which is
66 <     * always a power of two. The array is never allowed to become
58 <     * full, except transiently within an addX method where it is
59 <     * resized (see doubleCapacity) immediately upon becoming full,
60 <     * thus avoiding head and tail wrapping around to equal each
61 <     * other.  We also guarantee that all array cells not holding
62 <     * deque elements are always null.
64 >     * The array in which the elements of the deque are stored.
65 >     * We guarantee that all array cells not holding deque elements
66 >     * are always null.
67       */
68 <    private transient E[] elements;
68 >    transient Object[] elements;
69  
70      /**
71       * The index of the element at the head of the deque (which is the
72       * element that would be removed by remove() or pop()); or an
73 <     * arbitrary number equal to tail if the deque is empty.
70 <     */
71 <    private transient int head;
72 <
73 <    /**
74 <     * The index at which the next element would be added to the tail
75 <     * of the deque (via addLast(E), add(E), or push(E)).
76 <     */
77 <    private transient int tail;
78 <
79 <    /**
80 <     * The minimum capacity that we'll use for a newly created deque.
81 <     * Must be a power of 2.
73 >     * arbitrary number 0 <= head < elements.length if the deque is empty.
74       */
75 <    private static final int MIN_INITIAL_CAPACITY = 8;
75 >    transient int head;
76  
77 <    // ******  Array allocation and resizing utilities ******
77 >    /** Number of elements in this collection. */
78 >    transient int size;
79  
80      /**
81 <     * Allocate empty array to hold the given number of elements.
82 <     *
83 <     * @param numElements  the number of elements to hold.
84 <     */
85 <    private void allocateElements(int numElements) {  
86 <        int initialCapacity = MIN_INITIAL_CAPACITY;
87 <        // Find the best power of two to hold elements.
88 <        // Tests "<=" because arrays aren't kept full.
89 <        if (numElements >= initialCapacity) {
90 <            initialCapacity = numElements;
91 <            initialCapacity |= (initialCapacity >>>  1);
92 <            initialCapacity |= (initialCapacity >>>  2);
93 <            initialCapacity |= (initialCapacity >>>  4);
94 <            initialCapacity |= (initialCapacity >>>  8);
95 <            initialCapacity |= (initialCapacity >>> 16);
96 <            initialCapacity++;
81 >     * The maximum size of array to allocate.
82 >     * Some VMs reserve some header words in an array.
83 >     * Attempts to allocate larger arrays may result in
84 >     * OutOfMemoryError: Requested array size exceeds VM limit
85 >     */
86 >    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
87 >
88 >    /**
89 >     * Increases the capacity of this deque by at least the given amount.
90 >     *
91 >     * @param needed the required minimum extra capacity; must be positive
92 >     */
93 >    private void grow(int needed) {
94 >        // overflow-conscious code
95 >        // checkInvariants();
96 >        int oldCapacity = elements.length;
97 >        int newCapacity;
98 >        // Double size if small; else grow by 50%
99 >        int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
100 >        if (jump < needed
101 >            || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
102 >            newCapacity = newCapacity(needed, jump);
103 >        elements = Arrays.copyOf(elements, newCapacity);
104 >        if (oldCapacity - head < size) {
105 >            // wrap around; slide first leg forward to end of array
106 >            int newSpace = newCapacity - oldCapacity;
107 >            System.arraycopy(elements, head,
108 >                             elements, head + newSpace,
109 >                             oldCapacity - head);
110 >            Arrays.fill(elements, head, head + newSpace, null);
111 >            head += newSpace;
112 >        }
113 >        // checkInvariants();
114 >    }
115  
116 <            if (initialCapacity < 0)   // Too many elements, must back off
117 <                initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
116 >    /** Capacity calculation for edge conditions, especially overflow. */
117 >    private int newCapacity(int needed, int jump) {
118 >        int oldCapacity = elements.length;
119 >        int minCapacity;
120 >        if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
121 >            if (minCapacity < 0)
122 >                throw new IllegalStateException("Sorry, deque too big");
123 >            return Integer.MAX_VALUE;
124          }
125 <        elements = (E[]) new Object[initialCapacity];
125 >        if (needed > jump)
126 >            return minCapacity;
127 >        return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
128 >            ? oldCapacity + jump
129 >            : MAX_ARRAY_SIZE;
130      }
131  
132      /**
133 <     * Double the capacity of this deque.  Call only when full, i.e.,
134 <     * when head and tail have wrapped around to become equal.
133 >     * Increases the internal storage of this collection, if necessary,
134 >     * to ensure that it can hold at least the given number of elements.
135 >     *
136 >     * @param minCapacity the desired minimum capacity
137 >     * @since 9
138       */
139 <    private void doubleCapacity() {
140 <        assert head == tail;
141 <        int p = head;
142 <        int n = elements.length;
119 <        int r = n - p; // number of elements to the right of p
120 <        int newCapacity = n << 1;
121 <        if (newCapacity < 0)
122 <            throw new IllegalStateException("Sorry, deque too big");
123 <        Object[] a = new Object[newCapacity];
124 <        System.arraycopy(elements, p, a, 0, r);
125 <        System.arraycopy(elements, 0, a, r, p);
126 <        elements = (E[])a;
127 <        head = 0;
128 <        tail = n;
139 >    public void ensureCapacity(int minCapacity) {
140 >        if (minCapacity > elements.length)
141 >            grow(minCapacity - elements.length);
142 >        // checkInvariants();
143      }
144  
145      /**
146 <     * Copy the elements from our element array into the specified array,
133 <     * in order (from first to last element in the deque).  It is assumed
134 <     * that the array is large enough to hold all elements in the deque.
146 >     * Minimizes the internal storage of this collection.
147       *
148 <     * @return its argument
148 >     * @since 9
149       */
150 <    private <T> T[] copyElements(T[] a) {
151 <        if (head < tail) {
152 <            System.arraycopy(elements, head, a, 0, size());
153 <        } else if (head > tail) {
142 <            int headPortionLen = elements.length - head;
143 <            System.arraycopy(elements, head, a, 0, headPortionLen);
144 <            System.arraycopy(elements, 0, a, headPortionLen, tail);
150 >    public void trimToSize() {
151 >        if (size < elements.length) {
152 >            elements = toArray();
153 >            head = 0;
154          }
155 <        return a;
155 >        // checkInvariants();
156      }
157  
158      /**
159 <     * Constructs an empty array deque with the an initial capacity
159 >     * Constructs an empty array deque with an initial capacity
160       * sufficient to hold 16 elements.
161       */
162      public ArrayDeque() {
163 <        elements = (E[]) new Object[16];
163 >        elements = new Object[16];
164      }
165  
166      /**
167       * Constructs an empty array deque with an initial capacity
168       * sufficient to hold the specified number of elements.
169       *
170 <     * @param numElements  lower bound on initial capacity of the deque
170 >     * @param numElements lower bound on initial capacity of the deque
171       */
172      public ArrayDeque(int numElements) {
173 <        allocateElements(numElements);
173 >        elements = new Object[numElements];
174      }
175  
176      /**
# Line 175 | Line 184 | public class ArrayDeque<E> extends Abstr
184       * @throws NullPointerException if the specified collection is null
185       */
186      public ArrayDeque(Collection<? extends E> c) {
187 <        allocateElements(c.size());
188 <        addAll(c);
187 >        Object[] elements = c.toArray();
188 >        // defend against c.toArray (incorrectly) not returning Object[]
189 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
190 >        if (elements.getClass() != Object[].class)
191 >            elements = Arrays.copyOf(elements, size, Object[].class);
192 >        for (Object obj : elements)
193 >            Objects.requireNonNull(obj);
194 >        size = elements.length;
195 >        this.elements = elements;
196      }
197  
198 <    // The main insertion and extraction methods are addFirst,
199 <    // addLast, pollFirst, pollLast. The other methods are defined in
200 <    // terms of these.
198 >    /**
199 >     * Returns the array index of the last element.
200 >     * May return invalid index -1 if there are no elements.
201 >     */
202 >    final int tail() {
203 >        return add(head, size - 1, elements.length);
204 >    }
205  
206      /**
207 <     * Inserts the specified element to the front this deque.
208 <     *
189 <     * @param e the element to insert
190 <     * @throws NullPointerException if <tt>e</tt> is null
207 >     * Adds i and j, mod modulus.
208 >     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
209       */
210 <    public void addFirst(E e) {
211 <        if (e == null)
212 <            throw new NullPointerException();
195 <        elements[head = (head - 1) & (elements.length - 1)] = e;
196 <        if (head == tail)
197 <            doubleCapacity();
210 >    static final int add(int i, int j, int modulus) {
211 >        if ((i += j) - modulus >= 0) i -= modulus;
212 >        return i;
213      }
214  
215      /**
216 <     * Inserts the specified element to the end this deque.
217 <     * This method is equivalent to {@link Collection#add} and
203 <     * {@link #push}.
204 <     *
205 <     * @param e the element to insert
206 <     * @throws NullPointerException if <tt>e</tt> is null
216 >     * Increments i, mod modulus.
217 >     * Precondition and postcondition: 0 <= i < modulus.
218       */
219 <    public void addLast(E e) {
219 >    static final int inc(int i, int modulus) {
220 >        if (++i == modulus) i = 0;
221 >        return i;
222 >    }
223 >
224 >    /**
225 >     * Decrements i, mod modulus.
226 >     * Precondition and postcondition: 0 <= i < modulus.
227 >     */
228 >    static final int dec(int i, int modulus) {
229 >        if (--i < 0) i += modulus;
230 >        return i;
231 >    }
232 >
233 >    /**
234 >     * Returns element at array index i.
235 >     */
236 >    @SuppressWarnings("unchecked")
237 >    final E elementAt(int i) {
238 >        return (E) elements[i];
239 >    }
240 >
241 >    /**
242 >     * A version of elementAt that checks for null elements.
243 >     * This check doesn't catch all possible comodifications,
244 >     * but does catch ones that corrupt traversal.
245 >     */
246 >    E checkedElementAt(Object[] elements, int i) {
247 >        @SuppressWarnings("unchecked") E e = (E) elements[i];
248          if (e == null)
249 <            throw new NullPointerException();
250 <        elements[tail] = e;
212 <        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
213 <            doubleCapacity();
249 >            throw new ConcurrentModificationException();
250 >        return e;
251      }
252  
253 +    // The main insertion and extraction methods are addFirst,
254 +    // addLast, pollFirst, pollLast. The other methods are defined in
255 +    // terms of these.
256 +
257      /**
258 <     * Retrieves and removes the first element of this deque, or
218 <     * <tt>null</tt> if this deque is empty.
258 >     * Inserts the specified element at the front of this deque.
259       *
260 <     * @return the first element of this deque, or <tt>null</tt> if
261 <     *     this deque is empty
260 >     * @param e the element to add
261 >     * @throws NullPointerException if the specified element is null
262       */
263 <    public E pollFirst() {
264 <        int h = head;
265 <        E result = elements[h]; // Element is null if deque empty
266 <        if (result == null)
267 <            return null;
268 <        elements[h] = null;     // Must null out slot
269 <        head = (h + 1) & (elements.length - 1);
270 <        return result;
263 >    public void addFirst(E e) {
264 >        // checkInvariants();
265 >        Objects.requireNonNull(e);
266 >        Object[] elements;
267 >        int capacity, s = size;
268 >        while (s == (capacity = (elements = this.elements).length))
269 >            grow(1);
270 >        elements[head = dec(head, capacity)] = e;
271 >        size = s + 1;
272      }
273  
274      /**
275 <     * Retrieves and removes the last element of this deque, or
276 <     * <tt>null</tt> if this deque is empty.
275 >     * Inserts the specified element at the end of this deque.
276 >     *
277 >     * <p>This method is equivalent to {@link #add}.
278       *
279 <     * @return the last element of this deque, or <tt>null</tt> if
280 <     *     this deque is empty
279 >     * @param e the element to add
280 >     * @throws NullPointerException if the specified element is null
281       */
282 <    public E pollLast() {
283 <        int t = (tail - 1) & (elements.length - 1);
284 <        E result = elements[t];
285 <        if (result == null)
286 <            return null;
287 <        elements[t] = null;
288 <        tail = t;
289 <        return result;
282 >    public void addLast(E e) {
283 >        // checkInvariants();
284 >        Objects.requireNonNull(e);
285 >        Object[] elements;
286 >        int capacity, s = size;
287 >        while (s == (capacity = (elements = this.elements).length))
288 >            grow(1);
289 >        elements[add(head, s, capacity)] = e;
290 >        size = s + 1;
291 >    }
292 >
293 >    /**
294 >     * Adds all of the elements in the specified collection at the end
295 >     * of this deque, as if by calling {@link #addLast} on each one,
296 >     * in the order that they are returned by the collection's
297 >     * iterator.
298 >     *
299 >     * @param c the elements to be inserted into this deque
300 >     * @return {@code true} if this deque changed as a result of the call
301 >     * @throws NullPointerException if the specified collection or any
302 >     *         of its elements are null
303 >     */
304 >    @Override
305 >    public boolean addAll(Collection<? extends E> c) {
306 >        // checkInvariants();
307 >        Object[] a, elements;
308 >        int len, capacity, s = size;
309 >        if ((len = (a = c.toArray()).length) == 0)
310 >            return false;
311 >        while ((capacity = (elements = this.elements).length) - s < len)
312 >            grow(len - (capacity - s));
313 >        int i = add(head, s, capacity);
314 >        for (Object x : a) {
315 >            Objects.requireNonNull(x);
316 >            elements[i] = x;
317 >            i = inc(i, capacity);
318 >            size++;
319 >        }
320 >        return true;
321      }
322  
323      /**
324 <     * Inserts the specified element to the front this deque.
324 >     * Inserts the specified element at the front of this deque.
325       *
326 <     * @param e the element to insert
327 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerFirst})
328 <     * @throws NullPointerException if <tt>e</tt> is null
326 >     * @param e the element to add
327 >     * @return {@code true} (as specified by {@link Deque#offerFirst})
328 >     * @throws NullPointerException if the specified element is null
329       */
330      public boolean offerFirst(E e) {
331          addFirst(e);
# Line 260 | Line 333 | public class ArrayDeque<E> extends Abstr
333      }
334  
335      /**
336 <     * Inserts the specified element to the end this deque.
336 >     * Inserts the specified element at the end of this deque.
337       *
338 <     * @param e the element to insert
339 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerLast})
340 <     * @throws NullPointerException if <tt>e</tt> is null
338 >     * @param e the element to add
339 >     * @return {@code true} (as specified by {@link Deque#offerLast})
340 >     * @throws NullPointerException if the specified element is null
341       */
342      public boolean offerLast(E e) {
343          addLast(e);
# Line 272 | Line 345 | public class ArrayDeque<E> extends Abstr
345      }
346  
347      /**
348 <     * Retrieves and removes the first element of this deque.  This method
276 <     * differs from the <tt>pollFirst</tt> method in that it throws an
277 <     * exception if this deque is empty.
278 <     *
279 <     * @return the first element of this deque
280 <     * @throws NoSuchElementException if this deque is empty
348 >     * @throws NoSuchElementException {@inheritDoc}
349       */
350      public E removeFirst() {
351 +        // checkInvariants();
352          E x = pollFirst();
353          if (x == null)
354              throw new NoSuchElementException();
# Line 287 | Line 356 | public class ArrayDeque<E> extends Abstr
356      }
357  
358      /**
359 <     * Retrieves and removes the last element of this deque.  This method
291 <     * differs from the <tt>pollLast</tt> method in that it throws an
292 <     * exception if this deque is empty.
293 <     *
294 <     * @return the last element of this deque
295 <     * @throws NoSuchElementException if this deque is empty
359 >     * @throws NoSuchElementException {@inheritDoc}
360       */
361      public E removeLast() {
362 +        // checkInvariants();
363          E x = pollLast();
364          if (x == null)
365              throw new NoSuchElementException();
366          return x;
367      }
368  
369 <    /**
370 <     * Retrieves, but does not remove, the first element of this deque,
371 <     * returning <tt>null</tt> if this deque is empty.
372 <     *
373 <     * @return the first element of this deque, or <tt>null</tt> if
374 <     *     this deque is empty
375 <     */
376 <    public E peekFirst() {
377 <        return elements[head]; // elements[head] is null if deque empty
369 >    public E pollFirst() {
370 >        // checkInvariants();
371 >        final int s, h;
372 >        if ((s = size) == 0)
373 >            return null;
374 >        final Object[] elements = this.elements;
375 >        @SuppressWarnings("unchecked") E e = (E) elements[h = head];
376 >        elements[h] = null;
377 >        head = inc(h, elements.length);
378 >        size = s - 1;
379 >        return e;
380      }
381  
382 <    /**
383 <     * Retrieves, but does not remove, the last element of this deque,
384 <     * returning <tt>null</tt> if this deque is empty.
385 <     *
386 <     * @return the last element of this deque, or <tt>null</tt> if this deque
387 <     *     is empty
388 <     */
389 <    public E peekLast() {
390 <        return elements[(tail - 1) & (elements.length - 1)];
382 >    public E pollLast() {
383 >        // checkInvariants();
384 >        final int s, tail;
385 >        if ((s = size) == 0)
386 >            return null;
387 >        final Object[] elements = this.elements;
388 >        @SuppressWarnings("unchecked")
389 >        E e = (E) elements[tail = add(head, s - 1, elements.length)];
390 >        elements[tail] = null;
391 >        size = s - 1;
392 >        return e;
393      }
394  
395      /**
396 <     * Retrieves, but does not remove, the first element of this
328 <     * deque.  This method differs from the <tt>peek</tt> method only
329 <     * in that it throws an exception if this deque is empty.
330 <     *
331 <     * @return the first element of this deque
332 <     * @throws NoSuchElementException if this deque is empty
396 >     * @throws NoSuchElementException {@inheritDoc}
397       */
398      public E getFirst() {
399 <        E x = elements[head];
400 <        if (x == null)
401 <            throw new NoSuchElementException();
338 <        return x;
399 >        // checkInvariants();
400 >        if (size == 0) throw new NoSuchElementException();
401 >        return elementAt(head);
402      }
403  
404      /**
405 <     * Retrieves, but does not remove, the last element of this
343 <     * deque.  This method differs from the <tt>peek</tt> method only
344 <     * in that it throws an exception if this deque is empty.
345 <     *
346 <     * @return the last element of this deque
347 <     * @throws NoSuchElementException if this deque is empty
405 >     * @throws NoSuchElementException {@inheritDoc}
406       */
407      public E getLast() {
408 <        E x = elements[(tail - 1) & (elements.length - 1)];
409 <        if (x == null)
410 <            throw new NoSuchElementException();
411 <        return x;
408 >        // checkInvariants();
409 >        if (size == 0) throw new NoSuchElementException();
410 >        return elementAt(tail());
411 >    }
412 >
413 >    public E peekFirst() {
414 >        // checkInvariants();
415 >        return (size == 0) ? null : elementAt(head);
416 >    }
417 >
418 >    public E peekLast() {
419 >        // checkInvariants();
420 >        return (size == 0) ? null : elementAt(tail());
421      }
422  
423      /**
424       * Removes the first occurrence of the specified element in this
425 <     * deque (when traversing the deque from head to tail).  If the deque
426 <     * does not contain the element, it is unchanged.
427 <     *
428 <     * @param e element to be removed from this deque, if present
429 <     * @return <tt>true</tt> if the deque contained the specified element
430 <     */
431 <    public boolean removeFirstOccurrence(Object e) {
432 <        if (e == null)
433 <            return false;
434 <        int mask = elements.length - 1;
435 <        int i = head;
436 <        E x;
437 <        while ( (x = elements[i]) != null) {
438 <            if (e.equals(x)) {
439 <                delete(i);
440 <                return true;
425 >     * deque (when traversing the deque from head to tail).
426 >     * If the deque does not contain the element, it is unchanged.
427 >     * More formally, removes the first element {@code e} such that
428 >     * {@code o.equals(e)} (if such an element exists).
429 >     * Returns {@code true} if this deque contained the specified element
430 >     * (or equivalently, if this deque changed as a result of the call).
431 >     *
432 >     * @param o element to be removed from this deque, if present
433 >     * @return {@code true} if the deque contained the specified element
434 >     */
435 >    public boolean removeFirstOccurrence(Object o) {
436 >        // checkInvariants();
437 >        if (o != null) {
438 >            final Object[] elements = this.elements;
439 >            final int capacity = elements.length;
440 >            for (int k = size, i = head; --k >= 0; i = inc(i, capacity)) {
441 >                if (o.equals(elements[i])) {
442 >                    delete(i);
443 >                    return true;
444 >                }
445              }
375            i = (i + 1) & mask;
446          }
447          return false;
448      }
449  
450      /**
451       * Removes the last occurrence of the specified element in this
452 <     * deque (when traversing the deque from head to tail).  If the deque
453 <     * does not contain the element, it is unchanged.
454 <     *
455 <     * @param e element to be removed from this deque, if present
456 <     * @return <tt>true</tt> if the deque contained the specified element
457 <     */
458 <    public boolean removeLastOccurrence(Object e) {
459 <        if (e == null)
460 <            return false;
461 <        int mask = elements.length - 1;
462 <        int i = (tail - 1) & mask;
463 <        E x;
464 <        while ( (x = elements[i]) != null) {
465 <            if (e.equals(x)) {
466 <                delete(i);
467 <                return true;
452 >     * deque (when traversing the deque from head to tail).
453 >     * If the deque does not contain the element, it is unchanged.
454 >     * More formally, removes the last element {@code e} such that
455 >     * {@code o.equals(e)} (if such an element exists).
456 >     * Returns {@code true} if this deque contained the specified element
457 >     * (or equivalently, if this deque changed as a result of the call).
458 >     *
459 >     * @param o element to be removed from this deque, if present
460 >     * @return {@code true} if the deque contained the specified element
461 >     */
462 >    public boolean removeLastOccurrence(Object o) {
463 >        if (o != null) {
464 >            final Object[] elements = this.elements;
465 >            final int capacity = elements.length;
466 >            for (int k = size, i = add(head, k - 1, capacity);
467 >                 --k >= 0; i = dec(i, capacity)) {
468 >                if (o.equals(elements[i])) {
469 >                    delete(i);
470 >                    return true;
471 >                }
472              }
399            i = (i - 1) & mask;
473          }
474          return false;
475      }
# Line 404 | Line 477 | public class ArrayDeque<E> extends Abstr
477      // *** Queue methods ***
478  
479      /**
480 <     * Inserts the specified element to the end of this deque.
408 <     *
409 <     * <p>This method is equivalent to {@link #offerLast}.
410 <     *
411 <     * @param e the element to insert
412 <     * @return <tt>true</tt> (as per the spec for {@link Queue#offer})
413 <     * @throws NullPointerException if <tt>e</tt> is null
414 <     */
415 <    public boolean offer(E e) {
416 <        return offerLast(e);
417 <    }
418 <
419 <    /**
420 <     * Inserts the specified element to the end of this deque.
480 >     * Inserts the specified element at the end of this deque.
481       *
482       * <p>This method is equivalent to {@link #addLast}.
483       *
484 <     * @param e the element to insert
485 <     * @return <tt>true</tt> (as per the spec for {@link Collection#add})
486 <     * @throws NullPointerException if <tt>e</tt> is null
484 >     * @param e the element to add
485 >     * @return {@code true} (as specified by {@link Collection#add})
486 >     * @throws NullPointerException if the specified element is null
487       */
488      public boolean add(E e) {
489          addLast(e);
# Line 431 | Line 491 | public class ArrayDeque<E> extends Abstr
491      }
492  
493      /**
494 <     * Retrieves and removes the head of the queue represented by
435 <     * this deque, or <tt>null</tt> if this deque is empty.  In other words,
436 <     * retrieves and removes the first element of this deque, or <tt>null</tt>
437 <     * if this deque is empty.
494 >     * Inserts the specified element at the end of this deque.
495       *
496 <     * <p>This method is equivalent to {@link #pollFirst}.
496 >     * <p>This method is equivalent to {@link #offerLast}.
497       *
498 <     * @return the first element of this deque, or <tt>null</tt> if
499 <     *     this deque is empty
498 >     * @param e the element to add
499 >     * @return {@code true} (as specified by {@link Queue#offer})
500 >     * @throws NullPointerException if the specified element is null
501       */
502 <    public E poll() {
503 <        return pollFirst();
502 >    public boolean offer(E e) {
503 >        return offerLast(e);
504      }
505  
506      /**
507       * Retrieves and removes the head of the queue represented by this deque.
508 <     * This method differs from the <tt>poll</tt> method in that it throws an
508 >     *
509 >     * This method differs from {@link #poll poll} only in that it throws an
510       * exception if this deque is empty.
511       *
512       * <p>This method is equivalent to {@link #removeFirst}.
513       *
514       * @return the head of the queue represented by this deque
515 <     * @throws NoSuchElementException if this deque is empty
515 >     * @throws NoSuchElementException {@inheritDoc}
516       */
517      public E remove() {
518          return removeFirst();
519      }
520  
521      /**
522 <     * Retrieves, but does not remove, the head of the queue represented by
523 <     * this deque, returning <tt>null</tt> if this deque is empty.
522 >     * Retrieves and removes the head of the queue represented by this deque
523 >     * (in other words, the first element of this deque), or returns
524 >     * {@code null} if this deque is empty.
525       *
526 <     * <p>This method is equivalent to {@link #peekFirst}
526 >     * <p>This method is equivalent to {@link #pollFirst}.
527       *
528       * @return the head of the queue represented by this deque, or
529 <     *     <tt>null</tt> if this deque is empty
529 >     *         {@code null} if this deque is empty
530       */
531 <    public E peek() {
532 <        return peekFirst();
531 >    public E poll() {
532 >        return pollFirst();
533      }
534  
535      /**
536       * Retrieves, but does not remove, the head of the queue represented by
537 <     * this deque.  This method differs from the <tt>peek</tt> method only in
537 >     * this deque.  This method differs from {@link #peek peek} only in
538       * that it throws an exception if this deque is empty.
539       *
540 <     * <p>This method is equivalent to {@link #getFirst}
540 >     * <p>This method is equivalent to {@link #getFirst}.
541       *
542       * @return the head of the queue represented by this deque
543 <     * @throws NoSuchElementException if this deque is empty
543 >     * @throws NoSuchElementException {@inheritDoc}
544       */
545      public E element() {
546          return getFirst();
547      }
548  
549 +    /**
550 +     * Retrieves, but does not remove, the head of the queue represented by
551 +     * this deque, or returns {@code null} if this deque is empty.
552 +     *
553 +     * <p>This method is equivalent to {@link #peekFirst}.
554 +     *
555 +     * @return the head of the queue represented by this deque, or
556 +     *         {@code null} if this deque is empty
557 +     */
558 +    public E peek() {
559 +        return peekFirst();
560 +    }
561 +
562      // *** Stack methods ***
563  
564      /**
565       * Pushes an element onto the stack represented by this deque.  In other
566 <     * words, inserts the element to the front this deque.
566 >     * words, inserts the element at the front of this deque.
567       *
568       * <p>This method is equivalent to {@link #addFirst}.
569       *
570       * @param e the element to push
571 <     * @throws NullPointerException if <tt>e</tt> is null
571 >     * @throws NullPointerException if the specified element is null
572       */
573      public void push(E e) {
574          addFirst(e);
# Line 508 | Line 581 | public class ArrayDeque<E> extends Abstr
581       * <p>This method is equivalent to {@link #removeFirst()}.
582       *
583       * @return the element at the front of this deque (which is the top
584 <     *     of the stack represented by this deque)
585 <     * @throws NoSuchElementException if this deque is empty
584 >     *         of the stack represented by this deque)
585 >     * @throws NoSuchElementException {@inheritDoc}
586       */
587      public E pop() {
588          return removeFirst();
589      }
590  
591      /**
592 <     * Remove the element at the specified position in the elements array,
593 <     * adjusting head, tail, and size as necessary.  This can result in
594 <     * motion of elements backwards or forwards in the array.
595 <     *
596 <     * <p>This method is called delete rather than remove to emphasize
597 <     * that its semantics differ from those of List.remove(int).
598 <     *
592 >     * Removes the element at the specified position in the elements array.
593 >     * This can result in forward or backwards motion of array elements.
594 >     * We optimize for least element motion.
595 >     *
596 >     * <p>This method is called delete rather than remove to emphasize
597 >     * that its semantics differ from those of {@link List#remove(int)}.
598 >     *
599       * @return true if elements moved backwards
600       */
601 <    private boolean delete(int i) {
602 <        // Case 1: Deque doesn't wrap
603 <        // Case 2: Deque does wrap and removed element is in the head portion
604 <        if ((head < tail || tail == 0) || i >= head) {
605 <            System.arraycopy(elements, head, elements, head + 1, i - head);
606 <            elements[head] = null;
607 <            head = (head + 1) & (elements.length - 1);
601 >    boolean delete(int i) {
602 >        // checkInvariants();
603 >        final Object[] elements = this.elements;
604 >        final int capacity = elements.length;
605 >        final int h = head;
606 >        int front;              // number of elements before to-be-deleted elt
607 >        if ((front = i - h) < 0) front += capacity;
608 >        final int back = size - front - 1; // number of elements after
609 >        if (front < back) {
610 >            // move front elements forwards
611 >            if (h <= i) {
612 >                System.arraycopy(elements, h, elements, h + 1, front);
613 >            } else { // Wrap around
614 >                System.arraycopy(elements, 0, elements, 1, i);
615 >                elements[0] = elements[capacity - 1];
616 >                System.arraycopy(elements, h, elements, h + 1, front - (i + 1));
617 >            }
618 >            elements[h] = null;
619 >            head = inc(h, capacity);
620 >            size--;
621 >            // checkInvariants();
622              return false;
623 +        } else {
624 +            // move back elements backwards
625 +            int tail = tail();
626 +            if (i <= tail) {
627 +                System.arraycopy(elements, i + 1, elements, i, back);
628 +            } else { // Wrap around
629 +                int firstLeg = capacity - (i + 1);
630 +                System.arraycopy(elements, i + 1, elements, i, firstLeg);
631 +                elements[capacity - 1] = elements[0];
632 +                System.arraycopy(elements, 1, elements, 0, back - firstLeg - 1);
633 +            }
634 +            elements[tail] = null;
635 +            size--;
636 +            // checkInvariants();
637 +            return true;
638          }
537
538        // Case 3: Deque wraps and removed element is in the tail portion
539        tail--;
540        System.arraycopy(elements, i + 1, elements, i, tail - i);
541        elements[tail] = null;
542        return true;
639      }
640  
641      // *** Collection Methods ***
# Line 550 | Line 646 | public class ArrayDeque<E> extends Abstr
646       * @return the number of elements in this deque
647       */
648      public int size() {
649 <        return (tail - head) & (elements.length - 1);
649 >        return size;
650      }
651  
652      /**
653 <     * Returns <tt>true</tt> if this collection contains no elements.<p>
653 >     * Returns {@code true} if this deque contains no elements.
654       *
655 <     * @return <tt>true</tt> if this collection contains no elements.
655 >     * @return {@code true} if this deque contains no elements
656       */
657      public boolean isEmpty() {
658 <        return head == tail;
658 >        return size == 0;
659      }
660  
661      /**
# Line 567 | Line 663 | public class ArrayDeque<E> extends Abstr
663       * will be ordered from first (head) to last (tail).  This is the same
664       * order that elements would be dequeued (via successive calls to
665       * {@link #remove} or popped (via successive calls to {@link #pop}).
666 <     *
667 <     * @return an <tt>Iterator</tt> over the elements in this deque
666 >     *
667 >     * @return an iterator over the elements in this deque
668       */
669      public Iterator<E> iterator() {
670          return new DeqIterator();
671      }
672  
673 +    public Iterator<E> descendingIterator() {
674 +        return new DescendingIterator();
675 +    }
676 +
677      private class DeqIterator implements Iterator<E> {
678 <        /**
679 <         * Index of element to be returned by subsequent call to next.
580 <         */
581 <        private int cursor = head;
678 >        /** Index of element to be returned by subsequent call to next. */
679 >        int cursor;
680  
681 <        /**
682 <         * Tail recorded at construction (also in remove), to stop
585 <         * iterator and also to check for comodification.
586 <         */
587 <        private int fence = tail;
681 >        /** Number of elements yet to be returned. */
682 >        int remaining = size;
683  
684          /**
685           * Index of element returned by most recent call to next.
686           * Reset to -1 if element is deleted by a call to remove.
687           */
688 <        private int lastRet = -1;
688 >        int lastRet = -1;
689 >
690 >        DeqIterator() { cursor = head; }
691 >
692 >        int advance(int i, int modulus) {
693 >            return inc(i, modulus);
694 >        }
695 >
696 >        void doRemove() {
697 >            if (delete(lastRet))
698 >                // if left-shifted, undo advance in next()
699 >                cursor = dec(cursor, elements.length);
700 >        }
701  
702 <        public boolean hasNext() {
703 <            return cursor != fence;
702 >        public final boolean hasNext() {
703 >            return remaining > 0;
704          }
705  
706 <        public E next() {
707 <            E result;
601 <            if (cursor == fence)
706 >        public final E next() {
707 >            if (remaining == 0)
708                  throw new NoSuchElementException();
709 <            // This check doesn't catch all possible comodifications,
604 <            // but does catch the ones that corrupt traversal
605 <            if (tail != fence || (result = elements[cursor]) == null)
606 <                throw new ConcurrentModificationException();
709 >            E e = checkedElementAt(elements, cursor);
710              lastRet = cursor;
711 <            cursor = (cursor + 1) & (elements.length - 1);
712 <            return result;
711 >            cursor = advance(cursor, elements.length);
712 >            remaining--;
713 >            return e;
714          }
715  
716 <        public void remove() {
716 >        public final void remove() {
717              if (lastRet < 0)
718                  throw new IllegalStateException();
719 <            if (delete(lastRet))
616 <                cursor--;
719 >            doRemove();
720              lastRet = -1;
721 <            fence = tail;
721 >        }
722 >
723 >        public final void forEachRemaining(Consumer<? super E> action) {
724 >            Objects.requireNonNull(action);
725 >            final Object[] elements = ArrayDeque.this.elements;
726 >            final int capacity = elements.length;
727 >            int k = remaining;
728 >            remaining = 0;
729 >            for (int i = cursor; --k >= 0; i = advance(i, capacity))
730 >                action.accept(checkedElementAt(elements, i));
731 >        }
732 >    }
733 >
734 >    private class DescendingIterator extends DeqIterator {
735 >        DescendingIterator() { cursor = tail(); }
736 >
737 >        @Override int advance(int i, int modulus) {
738 >            return dec(i, modulus);
739 >        }
740 >
741 >        @Override void doRemove() {
742 >            if (!delete(lastRet))
743 >                // if right-shifted, undo advance in next
744 >                cursor = inc(cursor, elements.length);
745 >        }
746 >    }
747 >
748 >    /**
749 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
750 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
751 >     * deque.
752 >     *
753 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
754 >     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
755 >     * {@link Spliterator#NONNULL}.  Overriding implementations should document
756 >     * the reporting of additional characteristic values.
757 >     *
758 >     * @return a {@code Spliterator} over the elements in this deque
759 >     * @since 1.8
760 >     */
761 >    public Spliterator<E> spliterator() {
762 >        return new ArrayDequeSpliterator();
763 >    }
764 >
765 >    final class ArrayDequeSpliterator implements Spliterator<E> {
766 >        private int cursor;
767 >        private int remaining; // -1 until late-binding first use
768 >
769 >        /** Constructs late-binding spliterator over all elements. */
770 >        ArrayDequeSpliterator() {
771 >            this.remaining = -1;
772 >        }
773 >
774 >        /** Constructs spliterator over the given slice. */
775 >        ArrayDequeSpliterator(int cursor, int count) {
776 >            this.cursor = cursor;
777 >            this.remaining = count;
778 >        }
779 >
780 >        /** Ensures late-binding initialization; then returns remaining. */
781 >        private int remaining() {
782 >            if (remaining < 0) {
783 >                cursor = head;
784 >                remaining = size;
785 >            }
786 >            return remaining;
787 >        }
788 >
789 >        public ArrayDequeSpliterator trySplit() {
790 >            final int mid;
791 >            if ((mid = remaining() >> 1) > 0) {
792 >                int oldCursor = cursor;
793 >                cursor = add(cursor, mid, elements.length);
794 >                remaining -= mid;
795 >                return new ArrayDequeSpliterator(oldCursor, mid);
796 >            }
797 >            return null;
798 >        }
799 >
800 >        public void forEachRemaining(Consumer<? super E> action) {
801 >            Objects.requireNonNull(action);
802 >            final Object[] elements = ArrayDeque.this.elements;
803 >            final int capacity = elements.length;
804 >            int k = remaining();
805 >            remaining = 0;
806 >            for (int i = cursor; --k >= 0; i = inc(i, capacity))
807 >                action.accept(checkedElementAt(elements, i));
808 >        }
809 >
810 >        public boolean tryAdvance(Consumer<? super E> action) {
811 >            Objects.requireNonNull(action);
812 >            if (remaining() == 0)
813 >                return false;
814 >            action.accept(checkedElementAt(elements, cursor));
815 >            cursor = inc(cursor, elements.length);
816 >            remaining--;
817 >            return true;
818 >        }
819 >
820 >        public long estimateSize() {
821 >            return remaining();
822 >        }
823 >
824 >        public int characteristics() {
825 >            return Spliterator.NONNULL
826 >                | Spliterator.ORDERED
827 >                | Spliterator.SIZED
828 >                | Spliterator.SUBSIZED;
829          }
830      }
831  
832 +    @Override
833 +    public void forEach(Consumer<? super E> action) {
834 +        // checkInvariants();
835 +        Objects.requireNonNull(action);
836 +        final Object[] elements = this.elements;
837 +        final int capacity = elements.length;
838 +        for (int k = size, i = head; --k >= 0; i = inc(i, capacity))
839 +            action.accept(elementAt(i));
840 +        // checkInvariants();
841 +    }
842 +
843      /**
844 <     * Returns <tt>true</tt> if this deque contains the specified
845 <     * element.  More formally, returns <tt>true</tt> if and only if this
846 <     * deque contains at least one element <tt>e</tt> such that
847 <     * <tt>e.equals(o)</tt>.
844 >     * Replaces each element of this deque with the result of applying the
845 >     * operator to that element, as specified by {@link List#replaceAll}.
846 >     *
847 >     * @param operator the operator to apply to each element
848 >     * @since 9
849 >     */
850 >    public void replaceAll(UnaryOperator<E> operator) {
851 >        Objects.requireNonNull(operator);
852 >        final Object[] elements = this.elements;
853 >        final int capacity = elements.length;
854 >        for (int k = size, i = head; --k >= 0; i = inc(i, capacity))
855 >            elements[i] = operator.apply(elementAt(i));
856 >        // checkInvariants();
857 >    }
858 >
859 >    /**
860 >     * @throws NullPointerException {@inheritDoc}
861 >     */
862 >    @Override
863 >    public boolean removeIf(Predicate<? super E> filter) {
864 >        Objects.requireNonNull(filter);
865 >        return bulkRemove(filter);
866 >    }
867 >
868 >    /**
869 >     * @throws NullPointerException {@inheritDoc}
870 >     */
871 >    @Override
872 >    public boolean removeAll(Collection<?> c) {
873 >        Objects.requireNonNull(c);
874 >        return bulkRemove(e -> c.contains(e));
875 >    }
876 >
877 >    /**
878 >     * @throws NullPointerException {@inheritDoc}
879 >     */
880 >    @Override
881 >    public boolean retainAll(Collection<?> c) {
882 >        Objects.requireNonNull(c);
883 >        return bulkRemove(e -> !c.contains(e));
884 >    }
885 >
886 >    /** Implementation of bulk remove methods. */
887 >    private boolean bulkRemove(Predicate<? super E> filter) {
888 >        // checkInvariants();
889 >        final Object[] elements = this.elements;
890 >        final int capacity = elements.length;
891 >        int i = head, j = i, remaining = size, deleted = 0;
892 >        try {
893 >            for (; remaining > 0; remaining--, i = inc(i, capacity)) {
894 >                @SuppressWarnings("unchecked") E e = (E) elements[i];
895 >                if (filter.test(e))
896 >                    deleted++;
897 >                else {
898 >                    if (j != i)
899 >                        elements[j] = e;
900 >                    j = inc(j, capacity);
901 >                }
902 >            }
903 >            return deleted > 0;
904 >        } catch (Throwable ex) {
905 >            for (; remaining > 0;
906 >                 remaining--, i = inc(i, capacity), j = inc(j, capacity))
907 >                elements[j] = elements[i];
908 >            throw ex;
909 >        } finally {
910 >            size -= deleted;
911 >            for (; --deleted >= 0; j = inc(j, capacity))
912 >                elements[j] = null;
913 >            // checkInvariants();
914 >        }
915 >    }
916 >
917 >    /**
918 >     * Returns {@code true} if this deque contains the specified element.
919 >     * More formally, returns {@code true} if and only if this deque contains
920 >     * at least one element {@code e} such that {@code o.equals(e)}.
921       *
922       * @param o object to be checked for containment in this deque
923 <     * @return <tt>true</tt> if this deque contains the specified element
923 >     * @return {@code true} if this deque contains the specified element
924       */
925      public boolean contains(Object o) {
926 <        if (o == null)
927 <            return false;
928 <        int mask = elements.length - 1;
929 <        int i = head;
930 <        E x;
931 <        while ( (x = elements[i]) != null) {
638 <            if (o.equals(x))
639 <                return true;
640 <            i = (i + 1) & mask;
926 >        if (o != null) {
927 >            final Object[] elements = this.elements;
928 >            final int capacity = elements.length;
929 >            for (int k = size, i = head; --k >= 0; i = inc(i, capacity))
930 >                if (o.equals(elements[i]))
931 >                    return true;
932          }
933          return false;
934      }
935  
936      /**
937       * Removes a single instance of the specified element from this deque.
938 <     * This method is equivalent to {@link #removeFirstOccurrence}.
938 >     * If the deque does not contain the element, it is unchanged.
939 >     * More formally, removes the first element {@code e} such that
940 >     * {@code o.equals(e)} (if such an element exists).
941 >     * Returns {@code true} if this deque contained the specified element
942 >     * (or equivalently, if this deque changed as a result of the call).
943       *
944 <     * @param e element to be removed from this deque, if present
945 <     * @return <tt>true</tt> if this deque contained the specified element
944 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
945 >     *
946 >     * @param o element to be removed from this deque, if present
947 >     * @return {@code true} if this deque contained the specified element
948       */
949 <    public boolean remove(Object e) {
950 <        return removeFirstOccurrence(e);
949 >    public boolean remove(Object o) {
950 >        return removeFirstOccurrence(o);
951      }
952  
953      /**
954       * Removes all of the elements from this deque.
955 +     * The deque will be empty after this call returns.
956       */
957      public void clear() {
958 <        int h = head;
959 <        int t = tail;
960 <        if (h != t) { // clear all cells
961 <            head = tail = 0;
962 <            int i = h;
963 <            int mask = elements.length - 1;
964 <            do {
965 <                elements[i] = null;
966 <                i = (i + 1) & mask;
669 <            } while(i != t);
958 >        final Object[] elements = this.elements;
959 >        final int capacity = elements.length;
960 >        final int h = this.head;
961 >        final int s = size;
962 >        if (capacity - h >= s)
963 >            Arrays.fill(elements, h, h + s, null);
964 >        else {
965 >            Arrays.fill(elements, h, capacity, null);
966 >            Arrays.fill(elements, 0, s - capacity + h, null);
967          }
968 +        size = head = 0;
969 +        // checkInvariants();
970      }
971  
972      /**
973 <     * Returns an array containing all of the elements in this list
974 <     * in the correct order.
973 >     * Returns an array containing all of the elements in this deque
974 >     * in proper sequence (from first to last element).
975 >     *
976 >     * <p>The returned array will be "safe" in that no references to it are
977 >     * maintained by this deque.  (In other words, this method must allocate
978 >     * a new array).  The caller is thus free to modify the returned array.
979       *
980 <     * @return an array containing all of the elements in this list
981 <     *         in the correct order
980 >     * <p>This method acts as bridge between array-based and collection-based
981 >     * APIs.
982 >     *
983 >     * @return an array containing all of the elements in this deque
984       */
985      public Object[] toArray() {
986 <        return copyElements(new Object[size()]);
986 >        final int head = this.head;
987 >        final int firstLeg;
988 >        Object[] a = Arrays.copyOfRange(elements, head, head + size);
989 >        if ((firstLeg = elements.length - head) < size)
990 >            System.arraycopy(elements, 0, a, firstLeg, size - firstLeg);
991 >        return a;
992      }
993  
994      /**
995 <     * Returns an array containing all of the elements in this deque in the
996 <     * correct order; the runtime type of the returned array is that of the
997 <     * specified array.  If the deque fits in the specified array, it is
998 <     * returned therein.  Otherwise, a new array is allocated with the runtime
999 <     * type of the specified array and the size of this deque.
995 >     * Returns an array containing all of the elements in this deque in
996 >     * proper sequence (from first to last element); the runtime type of the
997 >     * returned array is that of the specified array.  If the deque fits in
998 >     * the specified array, it is returned therein.  Otherwise, a new array
999 >     * is allocated with the runtime type of the specified array and the
1000 >     * size of this deque.
1001 >     *
1002 >     * <p>If this deque fits in the specified array with room to spare
1003 >     * (i.e., the array has more elements than this deque), the element in
1004 >     * the array immediately following the end of the deque is set to
1005 >     * {@code null}.
1006 >     *
1007 >     * <p>Like the {@link #toArray()} method, this method acts as bridge between
1008 >     * array-based and collection-based APIs.  Further, this method allows
1009 >     * precise control over the runtime type of the output array, and may,
1010 >     * under certain circumstances, be used to save allocation costs.
1011 >     *
1012 >     * <p>Suppose {@code x} is a deque known to contain only strings.
1013 >     * The following code can be used to dump the deque into a newly
1014 >     * allocated array of {@code String}:
1015       *
1016 <     * <p>If the deque fits in the specified array with room to spare (i.e.,
1017 <     * the array has more elements than the deque), the element in the array
1018 <     * immediately following the end of the collection is set to <tt>null</tt>.
1016 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1017 >     *
1018 >     * Note that {@code toArray(new Object[0])} is identical in function to
1019 >     * {@code toArray()}.
1020       *
1021       * @param a the array into which the elements of the deque are to
1022 <     *          be stored, if it is big enough; otherwise, a new array of the
1023 <     *          same runtime type is allocated for this purpose
1024 <     * @return an array containing the elements of the deque
1025 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
1026 <     *         of the runtime type of every element in this deque
1022 >     *          be stored, if it is big enough; otherwise, a new array of the
1023 >     *          same runtime type is allocated for this purpose
1024 >     * @return an array containing all of the elements in this deque
1025 >     * @throws ArrayStoreException if the runtime type of the specified array
1026 >     *         is not a supertype of the runtime type of every element in
1027 >     *         this deque
1028 >     * @throws NullPointerException if the specified array is null
1029       */
1030 +    @SuppressWarnings("unchecked")
1031      public <T> T[] toArray(T[] a) {
1032 <        int size = size();
1033 <        if (a.length < size)
1034 <            a = (T[])java.lang.reflect.Array.newInstance(
1035 <                    a.getClass().getComponentType(), size);
1036 <        copyElements(a);
1037 <        if (a.length > size)
1038 <            a[size] = null;
1032 >        final Object[] elements = this.elements;
1033 >        final int head = this.head;
1034 >        final int firstLeg;
1035 >        boolean wrap = (firstLeg = elements.length - head) < size;
1036 >        if (size > a.length) {
1037 >            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
1038 >                                         a.getClass());
1039 >        } else {
1040 >            System.arraycopy(elements, head, a, 0, wrap ? firstLeg : size);
1041 >            if (size < a.length)
1042 >                a[size] = null;
1043 >        }
1044 >        if (wrap)
1045 >            System.arraycopy(elements, 0, a, firstLeg, size - firstLeg);
1046          return a;
1047      }
1048  
# Line 718 | Line 1054 | public class ArrayDeque<E> extends Abstr
1054       * @return a copy of this deque
1055       */
1056      public ArrayDeque<E> clone() {
1057 <        try {
1057 >        try {
1058 >            @SuppressWarnings("unchecked")
1059              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
1060 <            // These two lines are currently faster than cloning the array:
724 <            result.elements = (E[]) new Object[elements.length];
725 <            System.arraycopy(elements, 0, result.elements, 0, elements.length);
1060 >            result.elements = Arrays.copyOf(elements, elements.length);
1061              return result;
1062 <
728 <        } catch (CloneNotSupportedException e) {
1062 >        } catch (CloneNotSupportedException e) {
1063              throw new AssertionError();
1064          }
1065      }
1066  
733    /**
734     * Appease the serialization gods.
735     */
1067      private static final long serialVersionUID = 2340985798034038923L;
1068  
1069      /**
1070 <     * Serialize this deque.
1070 >     * Saves this deque to a stream (that is, serializes it).
1071       *
1072 <     * @serialData The current size (<tt>int</tt>) of the deque,
1072 >     * @param s the stream
1073 >     * @throws java.io.IOException if an I/O error occurs
1074 >     * @serialData The current size ({@code int}) of the deque,
1075       * followed by all of its elements (each an object reference) in
1076       * first-to-last order.
1077       */
1078 <    private void writeObject(ObjectOutputStream s) throws IOException {
1078 >    private void writeObject(java.io.ObjectOutputStream s)
1079 >            throws java.io.IOException {
1080          s.defaultWriteObject();
1081  
1082          // Write out size
749        int size = size();
1083          s.writeInt(size);
1084  
1085          // Write out elements in order.
1086 <        int i = head;
1087 <        int mask = elements.length - 1;
1088 <        for (int j = 0; j < size; j++) {
1086 >        final Object[] elements = this.elements;
1087 >        final int capacity = elements.length;
1088 >        for (int k = size, i = head; --k >= 0; i = inc(i, capacity))
1089              s.writeObject(elements[i]);
757            i = (i + 1) & mask;
758        }
1090      }
1091  
1092      /**
1093 <     * Deserialize this deque.
1093 >     * Reconstitutes this deque from a stream (that is, deserializes it).
1094 >     * @param s the stream
1095 >     * @throws ClassNotFoundException if the class of a serialized object
1096 >     *         could not be found
1097 >     * @throws java.io.IOException if an I/O error occurs
1098       */
1099 <    private void readObject(ObjectInputStream s)
1100 <            throws IOException, ClassNotFoundException {
1099 >    private void readObject(java.io.ObjectInputStream s)
1100 >            throws java.io.IOException, ClassNotFoundException {
1101          s.defaultReadObject();
1102  
1103          // Read in size and allocate array
1104 <        int size = s.readInt();
770 <        allocateElements(size);
771 <        head = 0;
772 <        tail = size;
1104 >        elements = new Object[size = s.readInt()];
1105  
1106          // Read in all elements in the proper order.
1107          for (int i = 0; i < size; i++)
1108 <            elements[i] = (E)s.readObject();
1108 >            elements[i] = s.readObject();
1109 >    }
1110  
1111 +    /** debugging */
1112 +    private void checkInvariants() {
1113 +        try {
1114 +            int capacity = elements.length;
1115 +            assert size >= 0 && size <= capacity;
1116 +            assert head >= 0 && ((capacity == 0 && head == 0 && size == 0)
1117 +                                 || head < capacity);
1118 +            assert size == 0
1119 +                || (elements[head] != null && elements[tail()] != null);
1120 +            assert size == capacity
1121 +                || (elements[dec(head, capacity)] == null
1122 +                    && elements[inc(tail(), capacity)] == null);
1123 +        } catch (Throwable t) {
1124 +            System.err.printf("head=%d size=%d capacity=%d%n",
1125 +                              head, size, elements.length);
1126 +            System.err.printf("elements=%s%n",
1127 +                              Arrays.toString(elements));
1128 +            throw t;
1129 +        }
1130      }
1131 +
1132   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines