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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines