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.22 by dl, Fri Sep 16 23:59:27 2005 UTC vs.
Revision 1.136 by jsr166, Sun Nov 11 16:27:28 2018 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.util.*; // for javadoc (till 6280605 is fixed)
8 < 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 > // OPENJDK import jdk.internal.access.SharedSecrets;
13  
14   /**
15   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 16 | Line 20 | import java.io.*;
20   * {@link Stack} when used as a stack, and faster than {@link LinkedList}
21   * when used as a queue.
22   *
23 < * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
24 < * Exceptions include {@link #remove(Object) remove}, {@link
25 < * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
26 < * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
27 < * iterator.remove()}, and the bulk operations, all of which run in linear
28 < * time.
23 > * <p>Most {@code ArrayDeque} operations run in amortized constant time.
24 > * Exceptions include
25 > * {@link #remove(Object) remove},
26 > * {@link #removeFirstOccurrence removeFirstOccurrence},
27 > * {@link #removeLastOccurrence removeLastOccurrence},
28 > * {@link #contains contains},
29 > * {@link #iterator iterator.remove()},
30 > * and the bulk operations, all of which run in linear time.
31   *
32 < * <p>The iterators returned by this class's <tt>iterator</tt> method are
33 < * <i>fail-fast</i>: If the deque is modified at any time after the iterator
34 < * is created, in any way except through the iterator's own <tt>remove</tt>
35 < * method, the iterator will generally throw a {@link
32 > * <p>The iterators returned by this class's {@link #iterator() iterator}
33 > * method are <em>fail-fast</em>: If the deque is modified at any time after
34 > * the iterator is created, in any way except through the iterator's own
35 > * {@code remove} method, the iterator will generally throw a {@link
36   * ConcurrentModificationException}.  Thus, in the face of concurrent
37   * modification, the iterator fails quickly and cleanly, rather than risking
38   * arbitrary, non-deterministic behavior at an undetermined time in the
# Line 35 | Line 41 | import java.io.*;
41   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
42   * as it is, generally speaking, impossible to make any hard guarantees in the
43   * presence of unsynchronized concurrent modification.  Fail-fast iterators
44 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
44 > * throw {@code ConcurrentModificationException} on a best-effort basis.
45   * Therefore, it would be wrong to write a program that depended on this
46   * exception for its correctness: <i>the fail-fast behavior of iterators
47   * should be used only to detect bugs.</i>
# Line 45 | Line 51 | import java.io.*;
51   * Iterator} interfaces.
52   *
53   * <p>This class is a member of the
54 < * <a href="{@docRoot}/../guide/collections/index.html">
54 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
55   * Java Collections Framework</a>.
56   *
57   * @author  Josh Bloch and Doug Lea
58 + * @param <E> the type of elements held in this deque
59   * @since   1.6
53 * @param <E> the type of elements held in this collection
60   */
61   public class ArrayDeque<E> extends AbstractCollection<E>
62                             implements Deque<E>, Cloneable, Serializable
63   {
64 +    /*
65 +     * VMs excel at optimizing simple array loops where indices are
66 +     * incrementing or decrementing over a valid slice, e.g.
67 +     *
68 +     * for (int i = start; i < end; i++) ... elements[i]
69 +     *
70 +     * Because in a circular array, elements are in general stored in
71 +     * two disjoint such slices, we help the VM by writing unusual
72 +     * nested loops for all traversals over the elements.  Having only
73 +     * one hot inner loop body instead of two or three eases human
74 +     * maintenance and encourages VM loop inlining into the caller.
75 +     */
76 +
77      /**
78       * The array in which the elements of the deque are stored.
79 <     * The capacity of the deque is the length of this array, which is
80 <     * always a power of two. The array is never allowed to become
62 <     * full, except transiently within an addX method where it is
63 <     * resized (see doubleCapacity) immediately upon becoming full,
64 <     * thus avoiding head and tail wrapping around to equal each
65 <     * other.  We also guarantee that all array cells not holding
66 <     * deque elements are always null.
79 >     * All array cells not holding deque elements are always null.
80 >     * The array always has at least one null slot (at tail).
81       */
82 <    private transient E[] elements;
82 >    transient Object[] elements;
83  
84      /**
85       * The index of the element at the head of the deque (which is the
86       * element that would be removed by remove() or pop()); or an
87 <     * arbitrary number equal to tail if the deque is empty.
87 >     * arbitrary number 0 <= head < elements.length equal to tail if
88 >     * the deque is empty.
89       */
90 <    private transient int head;
90 >    transient int head;
91  
92      /**
93       * The index at which the next element would be added to the tail
94 <     * of the deque (via addLast(E), add(E), or push(E)).
95 <     */
81 <    private transient int tail;
82 <
83 <    /**
84 <     * The minimum capacity that we'll use for a newly created deque.
85 <     * Must be a power of 2.
94 >     * of the deque (via addLast(E), add(E), or push(E));
95 >     * elements[tail] is always null.
96       */
97 <    private static final int MIN_INITIAL_CAPACITY = 8;
88 <
89 <    // ******  Array allocation and resizing utilities ******
97 >    transient int tail;
98  
99      /**
100 <     * Allocate empty array to hold the given number of elements.
101 <     *
102 <     * @param numElements  the number of elements to hold
103 <     */
104 <    private void allocateElements(int numElements) {
105 <        int initialCapacity = MIN_INITIAL_CAPACITY;
106 <        // Find the best power of two to hold elements.
107 <        // Tests "<=" because arrays aren't kept full.
108 <        if (numElements >= initialCapacity) {
109 <            initialCapacity = numElements;
110 <            initialCapacity |= (initialCapacity >>>  1);
111 <            initialCapacity |= (initialCapacity >>>  2);
112 <            initialCapacity |= (initialCapacity >>>  4);
113 <            initialCapacity |= (initialCapacity >>>  8);
114 <            initialCapacity |= (initialCapacity >>> 16);
115 <            initialCapacity++;
100 >     * The maximum size of array to allocate.
101 >     * Some VMs reserve some header words in an array.
102 >     * Attempts to allocate larger arrays may result in
103 >     * OutOfMemoryError: Requested array size exceeds VM limit
104 >     */
105 >    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
106 >
107 >    /**
108 >     * Increases the capacity of this deque by at least the given amount.
109 >     *
110 >     * @param needed the required minimum extra capacity; must be positive
111 >     */
112 >    private void grow(int needed) {
113 >        // overflow-conscious code
114 >        final int oldCapacity = elements.length;
115 >        int newCapacity;
116 >        // Double capacity if small; else grow by 50%
117 >        int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
118 >        if (jump < needed
119 >            || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
120 >            newCapacity = newCapacity(needed, jump);
121 >        final Object[] es = elements = Arrays.copyOf(elements, newCapacity);
122 >        // Exceptionally, here tail == head needs to be disambiguated
123 >        if (tail < head || (tail == head && es[head] != null)) {
124 >            // wrap around; slide first leg forward to end of array
125 >            int newSpace = newCapacity - oldCapacity;
126 >            System.arraycopy(es, head,
127 >                             es, head + newSpace,
128 >                             oldCapacity - head);
129 >            for (int i = head, to = (head += newSpace); i < to; i++)
130 >                es[i] = null;
131 >        }
132 >        // checkInvariants();
133 >    }
134  
135 <            if (initialCapacity < 0)   // Too many elements, must back off
136 <                initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
135 >    /** Capacity calculation for edge conditions, especially overflow. */
136 >    private int newCapacity(int needed, int jump) {
137 >        final int oldCapacity = elements.length, minCapacity;
138 >        if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
139 >            if (minCapacity < 0)
140 >                throw new IllegalStateException("Sorry, deque too big");
141 >            return Integer.MAX_VALUE;
142          }
143 <        elements = (E[]) new Object[initialCapacity];
143 >        if (needed > jump)
144 >            return minCapacity;
145 >        return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
146 >            ? oldCapacity + jump
147 >            : MAX_ARRAY_SIZE;
148      }
149  
150      /**
151 <     * Double the capacity of this deque.  Call only when full, i.e.,
152 <     * when head and tail have wrapped around to become equal.
151 >     * Increases the internal storage of this collection, if necessary,
152 >     * to ensure that it can hold at least the given number of elements.
153 >     *
154 >     * @param minCapacity the desired minimum capacity
155 >     * @since TBD
156       */
157 <    private void doubleCapacity() {
158 <        assert head == tail;
159 <        int p = head;
160 <        int n = elements.length;
161 <        int r = n - p; // number of elements to the right of p
124 <        int newCapacity = n << 1;
125 <        if (newCapacity < 0)
126 <            throw new IllegalStateException("Sorry, deque too big");
127 <        Object[] a = new Object[newCapacity];
128 <        System.arraycopy(elements, p, a, 0, r);
129 <        System.arraycopy(elements, 0, a, r, p);
130 <        elements = (E[])a;
131 <        head = 0;
132 <        tail = n;
157 >    /* public */ void ensureCapacity(int minCapacity) {
158 >        int needed;
159 >        if ((needed = (minCapacity + 1 - elements.length)) > 0)
160 >            grow(needed);
161 >        // checkInvariants();
162      }
163  
164      /**
165 <     * Copies the elements from our element array into the specified array,
137 <     * in order (from first to last element in the deque).  It is assumed
138 <     * that the array is large enough to hold all elements in the deque.
165 >     * Minimizes the internal storage of this collection.
166       *
167 <     * @return its argument
167 >     * @since TBD
168       */
169 <    private <T> T[] copyElements(T[] a) {
170 <        if (head < tail) {
171 <            System.arraycopy(elements, head, a, 0, size());
172 <        } else if (head > tail) {
173 <            int headPortionLen = elements.length - head;
174 <            System.arraycopy(elements, head, a, 0, headPortionLen);
148 <            System.arraycopy(elements, 0, a, headPortionLen, tail);
169 >    /* public */ void trimToSize() {
170 >        int size;
171 >        if ((size = size()) + 1 < elements.length) {
172 >            elements = toArray(new Object[size + 1]);
173 >            head = 0;
174 >            tail = size;
175          }
176 <        return a;
176 >        // checkInvariants();
177      }
178  
179      /**
# Line 155 | Line 181 | public class ArrayDeque<E> extends Abstr
181       * sufficient to hold 16 elements.
182       */
183      public ArrayDeque() {
184 <        elements = (E[]) new Object[16];
184 >        elements = new Object[16 + 1];
185      }
186  
187      /**
188       * Constructs an empty array deque with an initial capacity
189       * sufficient to hold the specified number of elements.
190       *
191 <     * @param numElements  lower bound on initial capacity of the deque
191 >     * @param numElements lower bound on initial capacity of the deque
192       */
193      public ArrayDeque(int numElements) {
194 <        allocateElements(numElements);
194 >        elements =
195 >            new Object[(numElements < 1) ? 1 :
196 >                       (numElements == Integer.MAX_VALUE) ? Integer.MAX_VALUE :
197 >                       numElements + 1];
198      }
199  
200      /**
# Line 179 | Line 208 | public class ArrayDeque<E> extends Abstr
208       * @throws NullPointerException if the specified collection is null
209       */
210      public ArrayDeque(Collection<? extends E> c) {
211 <        allocateElements(c.size());
212 <        addAll(c);
211 >        this(c.size());
212 >        copyElements(c);
213 >    }
214 >
215 >    /**
216 >     * Circularly increments i, mod modulus.
217 >     * Precondition and postcondition: 0 <= i < modulus.
218 >     */
219 >    static final int inc(int i, int modulus) {
220 >        if (++i >= modulus) i = 0;
221 >        return i;
222 >    }
223 >
224 >    /**
225 >     * Circularly 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 - 1;
230 >        return i;
231 >    }
232 >
233 >    /**
234 >     * Circularly adds the given distance to index i, mod modulus.
235 >     * Precondition: 0 <= i < modulus, 0 <= distance <= modulus.
236 >     * @return index 0 <= i < modulus
237 >     */
238 >    static final int inc(int i, int distance, int modulus) {
239 >        if ((i += distance) - modulus >= 0) i -= modulus;
240 >        return i;
241 >    }
242 >
243 >    /**
244 >     * Subtracts j from i, mod modulus.
245 >     * Index i must be logically ahead of index j.
246 >     * Precondition: 0 <= i < modulus, 0 <= j < modulus.
247 >     * @return the "circular distance" from j to i; corner case i == j
248 >     * is disambiguated to "empty", returning 0.
249 >     */
250 >    static final int sub(int i, int j, int modulus) {
251 >        if ((i -= j) < 0) i += modulus;
252 >        return i;
253 >    }
254 >
255 >    /**
256 >     * Returns element at array index i.
257 >     * This is a slight abuse of generics, accepted by javac.
258 >     */
259 >    @SuppressWarnings("unchecked")
260 >    static final <E> E elementAt(Object[] es, int i) {
261 >        return (E) es[i];
262 >    }
263 >
264 >    /**
265 >     * A version of elementAt that checks for null elements.
266 >     * This check doesn't catch all possible comodifications,
267 >     * but does catch ones that corrupt traversal.
268 >     */
269 >    static final <E> E nonNullElementAt(Object[] es, int i) {
270 >        @SuppressWarnings("unchecked") E e = (E) es[i];
271 >        if (e == null)
272 >            throw new ConcurrentModificationException();
273 >        return e;
274      }
275  
276      // The main insertion and extraction methods are addFirst,
# Line 196 | Line 286 | public class ArrayDeque<E> extends Abstr
286      public void addFirst(E e) {
287          if (e == null)
288              throw new NullPointerException();
289 <        elements[head = (head - 1) & (elements.length - 1)] = e;
289 >        final Object[] es = elements;
290 >        es[head = dec(head, es.length)] = e;
291          if (head == tail)
292 <            doubleCapacity();
292 >            grow(1);
293 >        // checkInvariants();
294      }
295  
296      /**
# Line 212 | Line 304 | public class ArrayDeque<E> extends Abstr
304      public void addLast(E e) {
305          if (e == null)
306              throw new NullPointerException();
307 <        elements[tail] = e;
308 <        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
309 <            doubleCapacity();
307 >        final Object[] es = elements;
308 >        es[tail] = e;
309 >        if (head == (tail = inc(tail, es.length)))
310 >            grow(1);
311 >        // checkInvariants();
312 >    }
313 >
314 >    /**
315 >     * Adds all of the elements in the specified collection at the end
316 >     * of this deque, as if by calling {@link #addLast} on each one,
317 >     * in the order that they are returned by the collection's iterator.
318 >     *
319 >     * @param c the elements to be inserted into this deque
320 >     * @return {@code true} if this deque changed as a result of the call
321 >     * @throws NullPointerException if the specified collection or any
322 >     *         of its elements are null
323 >     */
324 >    public boolean addAll(Collection<? extends E> c) {
325 >        final int s, needed;
326 >        if ((needed = (s = size()) + c.size() + 1 - elements.length) > 0)
327 >            grow(needed);
328 >        copyElements(c);
329 >        // checkInvariants();
330 >        return size() > s;
331 >    }
332 >
333 >    private void copyElements(Collection<? extends E> c) {
334 >        c.forEach(this::addLast);
335      }
336  
337      /**
338       * Inserts the specified element at the front of this deque.
339       *
340       * @param e the element to add
341 <     * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
341 >     * @return {@code true} (as specified by {@link Deque#offerFirst})
342       * @throws NullPointerException if the specified element is null
343       */
344      public boolean offerFirst(E e) {
# Line 233 | Line 350 | public class ArrayDeque<E> extends Abstr
350       * Inserts the specified element at the end of this deque.
351       *
352       * @param e the element to add
353 <     * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
353 >     * @return {@code true} (as specified by {@link Deque#offerLast})
354       * @throws NullPointerException if the specified element is null
355       */
356      public boolean offerLast(E e) {
# Line 245 | Line 362 | public class ArrayDeque<E> extends Abstr
362       * @throws NoSuchElementException {@inheritDoc}
363       */
364      public E removeFirst() {
365 <        E x = pollFirst();
366 <        if (x == null)
365 >        E e = pollFirst();
366 >        if (e == null)
367              throw new NoSuchElementException();
368 <        return x;
368 >        // checkInvariants();
369 >        return e;
370      }
371  
372      /**
373       * @throws NoSuchElementException {@inheritDoc}
374       */
375      public E removeLast() {
376 <        E x = pollLast();
377 <        if (x == null)
376 >        E e = pollLast();
377 >        if (e == null)
378              throw new NoSuchElementException();
379 <        return x;
379 >        // checkInvariants();
380 >        return e;
381      }
382  
383      public E pollFirst() {
384 <        int h = head;
385 <        E result = elements[h]; // Element is null if deque empty
386 <        if (result == null)
387 <            return null;
388 <        elements[h] = null;     // Must null out slot
389 <        head = (h + 1) & (elements.length - 1);
390 <        return result;
384 >        final Object[] es;
385 >        final int h;
386 >        E e = elementAt(es = elements, h = head);
387 >        if (e != null) {
388 >            es[h] = null;
389 >            head = inc(h, es.length);
390 >        }
391 >        // checkInvariants();
392 >        return e;
393      }
394  
395      public E pollLast() {
396 <        int t = (tail - 1) & (elements.length - 1);
397 <        E result = elements[t];
398 <        if (result == null)
399 <            return null;
400 <        elements[t] = null;
401 <        tail = t;
402 <        return result;
396 >        final Object[] es;
397 >        final int t;
398 >        E e = elementAt(es = elements, t = dec(tail, es.length));
399 >        if (e != null)
400 >            es[tail = t] = null;
401 >        // checkInvariants();
402 >        return e;
403      }
404  
405      /**
406       * @throws NoSuchElementException {@inheritDoc}
407       */
408      public E getFirst() {
409 <        E x = elements[head];
410 <        if (x == null)
409 >        E e = elementAt(elements, head);
410 >        if (e == null)
411              throw new NoSuchElementException();
412 <        return x;
412 >        // checkInvariants();
413 >        return e;
414      }
415  
416      /**
417       * @throws NoSuchElementException {@inheritDoc}
418       */
419      public E getLast() {
420 <        E x = elements[(tail - 1) & (elements.length - 1)];
421 <        if (x == null)
420 >        final Object[] es = elements;
421 >        E e = elementAt(es, dec(tail, es.length));
422 >        if (e == null)
423              throw new NoSuchElementException();
424 <        return x;
424 >        // checkInvariants();
425 >        return e;
426      }
427  
428      public E peekFirst() {
429 <        return elements[head]; // elements[head] is null if deque empty
429 >        // checkInvariants();
430 >        return elementAt(elements, head);
431      }
432  
433      public E peekLast() {
434 <        return elements[(tail - 1) & (elements.length - 1)];
434 >        // checkInvariants();
435 >        final Object[] es;
436 >        return elementAt(es = elements, dec(tail, es.length));
437      }
438  
439      /**
440       * Removes the first occurrence of the specified element in this
441       * deque (when traversing the deque from head to tail).
442       * If the deque does not contain the element, it is unchanged.
443 <     * More formally, removes the first element <tt>e</tt> such that
444 <     * <tt>o.equals(e)</tt> (if such an element exists).
445 <     * Returns <tt>true</tt> if this deque contained the specified element
443 >     * More formally, removes the first element {@code e} such that
444 >     * {@code o.equals(e)} (if such an element exists).
445 >     * Returns {@code true} if this deque contained the specified element
446       * (or equivalently, if this deque changed as a result of the call).
447       *
448       * @param o element to be removed from this deque, if present
449 <     * @return <tt>true</tt> if the deque contained the specified element
449 >     * @return {@code true} if the deque contained the specified element
450       */
451      public boolean removeFirstOccurrence(Object o) {
452 <        if (o == null)
453 <            return false;
454 <        int mask = elements.length - 1;
455 <        int i = head;
456 <        E x;
457 <        while ( (x = elements[i]) != null) {
458 <            if (o.equals(x)) {
459 <                delete(i);
460 <                return true;
452 >        if (o != null) {
453 >            final Object[] es = elements;
454 >            for (int i = head, end = tail, to = (i <= end) ? end : es.length;
455 >                 ; i = 0, to = end) {
456 >                for (; i < to; i++)
457 >                    if (o.equals(es[i])) {
458 >                        delete(i);
459 >                        return true;
460 >                    }
461 >                if (to == end) break;
462              }
335            i = (i + 1) & mask;
463          }
464          return false;
465      }
# Line 341 | Line 468 | public class ArrayDeque<E> extends Abstr
468       * Removes the last occurrence of the specified element in this
469       * deque (when traversing the deque from head to tail).
470       * If the deque does not contain the element, it is unchanged.
471 <     * More formally, removes the last element <tt>e</tt> such that
472 <     * <tt>o.equals(e)</tt> (if such an element exists).
473 <     * Returns <tt>true</tt> if this deque contained the specified element
471 >     * More formally, removes the last element {@code e} such that
472 >     * {@code o.equals(e)} (if such an element exists).
473 >     * Returns {@code true} if this deque contained the specified element
474       * (or equivalently, if this deque changed as a result of the call).
475       *
476       * @param o element to be removed from this deque, if present
477 <     * @return <tt>true</tt> if the deque contained the specified element
477 >     * @return {@code true} if the deque contained the specified element
478       */
479      public boolean removeLastOccurrence(Object o) {
480 <        if (o == null)
481 <            return false;
482 <        int mask = elements.length - 1;
483 <        int i = (tail - 1) & mask;
484 <        E x;
485 <        while ( (x = elements[i]) != null) {
486 <            if (o.equals(x)) {
487 <                delete(i);
488 <                return true;
480 >        if (o != null) {
481 >            final Object[] es = elements;
482 >            for (int i = tail, end = head, to = (i >= end) ? end : 0;
483 >                 ; i = es.length, to = end) {
484 >                for (i--; i > to - 1; i--)
485 >                    if (o.equals(es[i])) {
486 >                        delete(i);
487 >                        return true;
488 >                    }
489 >                if (to == end) break;
490              }
363            i = (i - 1) & mask;
491          }
492          return false;
493      }
# Line 373 | Line 500 | public class ArrayDeque<E> extends Abstr
500       * <p>This method is equivalent to {@link #addLast}.
501       *
502       * @param e the element to add
503 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
503 >     * @return {@code true} (as specified by {@link Collection#add})
504       * @throws NullPointerException if the specified element is null
505       */
506      public boolean add(E e) {
# Line 387 | Line 514 | public class ArrayDeque<E> extends Abstr
514       * <p>This method is equivalent to {@link #offerLast}.
515       *
516       * @param e the element to add
517 <     * @return <tt>true</tt> (as specified by {@link Queue#offer})
517 >     * @return {@code true} (as specified by {@link Queue#offer})
518       * @throws NullPointerException if the specified element is null
519       */
520      public boolean offer(E e) {
# Line 397 | Line 524 | public class ArrayDeque<E> extends Abstr
524      /**
525       * Retrieves and removes the head of the queue represented by this deque.
526       *
527 <     * This method differs from {@link #poll poll} only in that it throws an
528 <     * exception if this deque is empty.
527 >     * This method differs from {@link #poll() poll()} only in that it
528 >     * throws an exception if this deque is empty.
529       *
530       * <p>This method is equivalent to {@link #removeFirst}.
531       *
# Line 412 | Line 539 | public class ArrayDeque<E> extends Abstr
539      /**
540       * Retrieves and removes the head of the queue represented by this deque
541       * (in other words, the first element of this deque), or returns
542 <     * <tt>null</tt> if this deque is empty.
542 >     * {@code null} if this deque is empty.
543       *
544       * <p>This method is equivalent to {@link #pollFirst}.
545       *
546       * @return the head of the queue represented by this deque, or
547 <     *         <tt>null</tt> if this deque is empty
547 >     *         {@code null} if this deque is empty
548       */
549      public E poll() {
550          return pollFirst();
# Line 439 | Line 566 | public class ArrayDeque<E> extends Abstr
566  
567      /**
568       * Retrieves, but does not remove, the head of the queue represented by
569 <     * this deque, or returns <tt>null</tt> if this deque is empty.
569 >     * this deque, or returns {@code null} if this deque is empty.
570       *
571       * <p>This method is equivalent to {@link #peekFirst}.
572       *
573       * @return the head of the queue represented by this deque, or
574 <     *         <tt>null</tt> if this deque is empty
574 >     *         {@code null} if this deque is empty
575       */
576      public E peek() {
577          return peekFirst();
# Line 480 | Line 607 | public class ArrayDeque<E> extends Abstr
607      }
608  
609      /**
610 <     * Removes the element at the specified position in the elements array,
611 <     * adjusting head and tail as necessary.  This can result in motion of
612 <     * elements backwards or forwards in the array.
610 >     * Removes the element at the specified position in the elements array.
611 >     * This can result in forward or backwards motion of array elements.
612 >     * We optimize for least element motion.
613       *
614       * <p>This method is called delete rather than remove to emphasize
615       * that its semantics differ from those of {@link List#remove(int)}.
616       *
617 <     * @return true if elements moved backwards
617 >     * @return true if elements near tail moved backwards
618       */
619 <    private boolean delete(int i) {
620 <        int mask = elements.length - 1;
621 <        int front = (i - head) & mask;
622 <        int back  = (tail - i) & mask;
623 <
624 <        // Invariant: head <= i < tail mod circularity
625 <        if (front >= ((tail - head) & mask))
626 <            throw new ConcurrentModificationException();
627 <
628 <        // Optimize for least element motion
629 <        if (front < back) {
630 <            if (head <= i) {
631 <                System.arraycopy(elements, head, elements, head + 1, front);
632 <            } else { // Wrap around
633 <                System.arraycopy(elements, 0, elements, 1, i);
634 <                elements[0] = elements[mask];
635 <                System.arraycopy(elements, head, elements, head + 1, mask - head);
636 <            }
637 <            elements[head] = null;
638 <            head = (head + 1) & mask;
619 >    boolean delete(int i) {
620 >        // checkInvariants();
621 >        final Object[] es = elements;
622 >        final int capacity = es.length;
623 >        final int h, t;
624 >        // number of elements before to-be-deleted elt
625 >        final int front = sub(i, h = head, capacity);
626 >        // number of elements after to-be-deleted elt
627 >        final int back = sub(t = tail, i, capacity) - 1;
628 >        if (front < back) {
629 >            // move front elements forwards
630 >            if (h <= i) {
631 >                System.arraycopy(es, h, es, h + 1, front);
632 >            } else { // Wrap around
633 >                System.arraycopy(es, 0, es, 1, i);
634 >                es[0] = es[capacity - 1];
635 >                System.arraycopy(es, h, es, h + 1, front - (i + 1));
636 >            }
637 >            es[h] = null;
638 >            head = inc(h, capacity);
639 >            // checkInvariants();
640              return false;
641 <        } else {
642 <            int t = tail;
643 <            tail = (tail - 1) & mask;
644 <            if (i < t) { // Copy the null tail as well
645 <                System.arraycopy(elements, i + 1, elements, i, back);
646 <            } else {     // Wrap around
647 <                System.arraycopy(elements, i + 1, elements, i, mask - i);
648 <                elements[mask] = elements[0];
649 <                System.arraycopy(elements, 1, elements, 0, t);
650 <            }
641 >        } else {
642 >            // move back elements backwards
643 >            tail = dec(t, capacity);
644 >            if (i <= tail) {
645 >                System.arraycopy(es, i + 1, es, i, back);
646 >            } else { // Wrap around
647 >                System.arraycopy(es, i + 1, es, i, capacity - (i + 1));
648 >                es[capacity - 1] = es[0];
649 >                System.arraycopy(es, 1, es, 0, t - 1);
650 >            }
651 >            es[tail] = null;
652 >            // checkInvariants();
653              return true;
654 <        }
654 >        }
655      }
656  
657      // *** Collection Methods ***
# Line 532 | Line 662 | public class ArrayDeque<E> extends Abstr
662       * @return the number of elements in this deque
663       */
664      public int size() {
665 <        return (tail - head) & (elements.length - 1);
665 >        return sub(tail, head, elements.length);
666      }
667  
668      /**
669 <     * Returns <tt>true</tt> if this deque contains no elements.
669 >     * Returns {@code true} if this deque contains no elements.
670       *
671 <     * @return <tt>true</tt> if this deque contains no elements
671 >     * @return {@code true} if this deque contains no elements
672       */
673      public boolean isEmpty() {
674          return head == tail;
# Line 561 | Line 691 | public class ArrayDeque<E> extends Abstr
691      }
692  
693      private class DeqIterator implements Iterator<E> {
694 <        /**
695 <         * Index of element to be returned by subsequent call to next.
566 <         */
567 <        private int cursor = head;
694 >        /** Index of element to be returned by subsequent call to next. */
695 >        int cursor;
696  
697 <        /**
698 <         * Tail recorded at construction (also in remove), to stop
571 <         * iterator and also to check for comodification.
572 <         */
573 <        private int fence = tail;
697 >        /** Number of elements yet to be returned. */
698 >        int remaining = size();
699  
700          /**
701           * Index of element returned by most recent call to next.
702           * Reset to -1 if element is deleted by a call to remove.
703           */
704 <        private int lastRet = -1;
704 >        int lastRet = -1;
705 >
706 >        DeqIterator() { cursor = head; }
707  
708 <        public boolean hasNext() {
709 <            return cursor != fence;
708 >        public final boolean hasNext() {
709 >            return remaining > 0;
710          }
711  
712          public E next() {
713 <            E result;
587 <            if (cursor == fence)
713 >            if (remaining <= 0)
714                  throw new NoSuchElementException();
715 <            // This check doesn't catch all possible comodifications,
716 <            // but does catch the ones that corrupt traversal
717 <            if (tail != fence || (result = elements[cursor]) == null)
718 <                throw new ConcurrentModificationException();
719 <            lastRet = cursor;
594 <            cursor = (cursor + 1) & (elements.length - 1);
595 <            return result;
715 >            final Object[] es = elements;
716 >            E e = nonNullElementAt(es, cursor);
717 >            cursor = inc(lastRet = cursor, es.length);
718 >            remaining--;
719 >            return e;
720          }
721  
722 <        public void remove() {
722 >        void postDelete(boolean leftShifted) {
723 >            if (leftShifted)
724 >                cursor = dec(cursor, elements.length);
725 >        }
726 >
727 >        public final void remove() {
728              if (lastRet < 0)
729                  throw new IllegalStateException();
730 <            if (delete(lastRet)) // if left-shifted, undo increment in next()
602 <                cursor = (cursor - 1) & (elements.length - 1);
730 >            postDelete(delete(lastRet));
731              lastRet = -1;
732 <            fence = tail;
732 >        }
733 >
734 >        public void forEachRemaining(Consumer<? super E> action) {
735 >            Objects.requireNonNull(action);
736 >            int r;
737 >            if ((r = remaining) <= 0)
738 >                return;
739 >            remaining = 0;
740 >            final Object[] es = elements;
741 >            if (es[cursor] == null || sub(tail, cursor, es.length) != r)
742 >                throw new ConcurrentModificationException();
743 >            for (int i = cursor, end = tail, to = (i <= end) ? end : es.length;
744 >                 ; i = 0, to = end) {
745 >                for (; i < to; i++)
746 >                    action.accept(elementAt(es, i));
747 >                if (to == end) {
748 >                    if (end != tail)
749 >                        throw new ConcurrentModificationException();
750 >                    lastRet = dec(end, es.length);
751 >                    break;
752 >                }
753 >            }
754          }
755      }
756  
757 +    private class DescendingIterator extends DeqIterator {
758 +        DescendingIterator() { cursor = dec(tail, elements.length); }
759  
760 <    private class DescendingIterator implements Iterator<E> {
761 <        /*
762 <         * This class is nearly a mirror-image of DeqIterator, using
763 <         * (tail-1) instead of head for initial cursor, (head-1)
764 <         * instead of tail for fence, and elements.length instead of -1
765 <         * for sentinel. It shares the same structure, but not many
766 <         * actual lines of code.
767 <         */
768 <        private int cursor = (tail - 1) & (elements.length - 1);
618 <        private int fence =  (head - 1) & (elements.length - 1);
619 <        private int lastRet = elements.length;
760 >        public final E next() {
761 >            if (remaining <= 0)
762 >                throw new NoSuchElementException();
763 >            final Object[] es = elements;
764 >            E e = nonNullElementAt(es, cursor);
765 >            cursor = dec(lastRet = cursor, es.length);
766 >            remaining--;
767 >            return e;
768 >        }
769  
770 <        public boolean hasNext() {
771 <            return cursor != fence;
770 >        void postDelete(boolean leftShifted) {
771 >            if (!leftShifted)
772 >                cursor = inc(cursor, elements.length);
773          }
774  
775 <        public E next() {
776 <            E result;
777 <            if (cursor == fence)
778 <                throw new NoSuchElementException();
779 <            if (((head - 1) & (elements.length - 1)) != fence ||
780 <                (result = elements[cursor]) == null)
775 >        public final void forEachRemaining(Consumer<? super E> action) {
776 >            Objects.requireNonNull(action);
777 >            int r;
778 >            if ((r = remaining) <= 0)
779 >                return;
780 >            remaining = 0;
781 >            final Object[] es = elements;
782 >            if (es[cursor] == null || sub(cursor, head, es.length) + 1 != r)
783                  throw new ConcurrentModificationException();
784 <            lastRet = cursor;
785 <            cursor = (cursor - 1) & (elements.length - 1);
786 <            return result;
784 >            for (int i = cursor, end = head, to = (i >= end) ? end : 0;
785 >                 ; i = es.length - 1, to = end) {
786 >                // hotspot generates faster code than for: i >= to !
787 >                for (; i > to - 1; i--)
788 >                    action.accept(elementAt(es, i));
789 >                if (to == end) {
790 >                    if (end != head)
791 >                        throw new ConcurrentModificationException();
792 >                    lastRet = end;
793 >                    break;
794 >                }
795 >            }
796          }
797 +    }
798  
799 <        public void remove() {
800 <            if (lastRet >= elements.length)
801 <                throw new IllegalStateException();
802 <            if (!delete(lastRet))
803 <                cursor = (cursor + 1) & (elements.length - 1);
804 <            lastRet = elements.length;
805 <            fence = (head - 1) & (elements.length - 1);
799 >    /**
800 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
801 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
802 >     * deque.
803 >     *
804 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
805 >     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
806 >     * {@link Spliterator#NONNULL}.  Overriding implementations should document
807 >     * the reporting of additional characteristic values.
808 >     *
809 >     * @return a {@code Spliterator} over the elements in this deque
810 >     * @since 1.8
811 >     */
812 >    public Spliterator<E> spliterator() {
813 >        return new DeqSpliterator();
814 >    }
815 >
816 >    final class DeqSpliterator implements Spliterator<E> {
817 >        private int fence;      // -1 until first use
818 >        private int cursor;     // current index, modified on traverse/split
819 >
820 >        /** Constructs late-binding spliterator over all elements. */
821 >        DeqSpliterator() {
822 >            this.fence = -1;
823 >        }
824 >
825 >        /** Constructs spliterator over the given range. */
826 >        DeqSpliterator(int origin, int fence) {
827 >            // assert 0 <= origin && origin < elements.length;
828 >            // assert 0 <= fence && fence < elements.length;
829 >            this.cursor = origin;
830 >            this.fence = fence;
831 >        }
832 >
833 >        /** Ensures late-binding initialization; then returns fence. */
834 >        private int getFence() { // force initialization
835 >            int t;
836 >            if ((t = fence) < 0) {
837 >                t = fence = tail;
838 >                cursor = head;
839 >            }
840 >            return t;
841 >        }
842 >
843 >        public DeqSpliterator trySplit() {
844 >            final Object[] es = elements;
845 >            final int i, n;
846 >            return ((n = sub(getFence(), i = cursor, es.length) >> 1) <= 0)
847 >                ? null
848 >                : new DeqSpliterator(i, cursor = inc(i, n, es.length));
849 >        }
850 >
851 >        public void forEachRemaining(Consumer<? super E> action) {
852 >            if (action == null)
853 >                throw new NullPointerException();
854 >            final int end = getFence(), cursor = this.cursor;
855 >            final Object[] es = elements;
856 >            if (cursor != end) {
857 >                this.cursor = end;
858 >                // null check at both ends of range is sufficient
859 >                if (es[cursor] == null || es[dec(end, es.length)] == null)
860 >                    throw new ConcurrentModificationException();
861 >                for (int i = cursor, to = (i <= end) ? end : es.length;
862 >                     ; i = 0, to = end) {
863 >                    for (; i < to; i++)
864 >                        action.accept(elementAt(es, i));
865 >                    if (to == end) break;
866 >                }
867 >            }
868 >        }
869 >
870 >        public boolean tryAdvance(Consumer<? super E> action) {
871 >            Objects.requireNonNull(action);
872 >            final Object[] es = elements;
873 >            if (fence < 0) { fence = tail; cursor = head; } // late-binding
874 >            final int i;
875 >            if ((i = cursor) == fence)
876 >                return false;
877 >            E e = nonNullElementAt(es, i);
878 >            cursor = inc(i, es.length);
879 >            action.accept(e);
880 >            return true;
881 >        }
882 >
883 >        public long estimateSize() {
884 >            return sub(getFence(), cursor, elements.length);
885 >        }
886 >
887 >        public int characteristics() {
888 >            return Spliterator.NONNULL
889 >                | Spliterator.ORDERED
890 >                | Spliterator.SIZED
891 >                | Spliterator.SUBSIZED;
892          }
893      }
894  
895      /**
896 <     * Returns <tt>true</tt> if this deque contains the specified element.
897 <     * More formally, returns <tt>true</tt> if and only if this deque contains
898 <     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
896 >     * @throws NullPointerException {@inheritDoc}
897 >     */
898 >    public void forEach(Consumer<? super E> action) {
899 >        Objects.requireNonNull(action);
900 >        final Object[] es = elements;
901 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
902 >             ; i = 0, to = end) {
903 >            for (; i < to; i++)
904 >                action.accept(elementAt(es, i));
905 >            if (to == end) {
906 >                if (end != tail) throw new ConcurrentModificationException();
907 >                break;
908 >            }
909 >        }
910 >        // checkInvariants();
911 >    }
912 >
913 >    /**
914 >     * Replaces each element of this deque with the result of applying the
915 >     * operator to that element, as specified by {@link List#replaceAll}.
916 >     *
917 >     * @param operator the operator to apply to each element
918 >     * @since TBD
919 >     */
920 >    /* public */ void replaceAll(UnaryOperator<E> operator) {
921 >        Objects.requireNonNull(operator);
922 >        final Object[] es = elements;
923 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
924 >             ; i = 0, to = end) {
925 >            for (; i < to; i++)
926 >                es[i] = operator.apply(elementAt(es, i));
927 >            if (to == end) {
928 >                if (end != tail) throw new ConcurrentModificationException();
929 >                break;
930 >            }
931 >        }
932 >        // checkInvariants();
933 >    }
934 >
935 >    /**
936 >     * @throws NullPointerException {@inheritDoc}
937 >     */
938 >    public boolean removeIf(Predicate<? super E> filter) {
939 >        Objects.requireNonNull(filter);
940 >        return bulkRemove(filter);
941 >    }
942 >
943 >    /**
944 >     * @throws NullPointerException {@inheritDoc}
945 >     */
946 >    public boolean removeAll(Collection<?> c) {
947 >        Objects.requireNonNull(c);
948 >        return bulkRemove(e -> c.contains(e));
949 >    }
950 >
951 >    /**
952 >     * @throws NullPointerException {@inheritDoc}
953 >     */
954 >    public boolean retainAll(Collection<?> c) {
955 >        Objects.requireNonNull(c);
956 >        return bulkRemove(e -> !c.contains(e));
957 >    }
958 >
959 >    /** Implementation of bulk remove methods. */
960 >    private boolean bulkRemove(Predicate<? super E> filter) {
961 >        // checkInvariants();
962 >        final Object[] es = elements;
963 >        // Optimize for initial run of survivors
964 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
965 >             ; i = 0, to = end) {
966 >            for (; i < to; i++)
967 >                if (filter.test(elementAt(es, i)))
968 >                    return bulkRemoveModified(filter, i);
969 >            if (to == end) {
970 >                if (end != tail) throw new ConcurrentModificationException();
971 >                break;
972 >            }
973 >        }
974 >        return false;
975 >    }
976 >
977 >    // A tiny bit set implementation
978 >
979 >    private static long[] nBits(int n) {
980 >        return new long[((n - 1) >> 6) + 1];
981 >    }
982 >    private static void setBit(long[] bits, int i) {
983 >        bits[i >> 6] |= 1L << i;
984 >    }
985 >    private static boolean isClear(long[] bits, int i) {
986 >        return (bits[i >> 6] & (1L << i)) == 0;
987 >    }
988 >
989 >    /**
990 >     * Helper for bulkRemove, in case of at least one deletion.
991 >     * Tolerate predicates that reentrantly access the collection for
992 >     * read (but writers still get CME), so traverse once to find
993 >     * elements to delete, a second pass to physically expunge.
994 >     *
995 >     * @param beg valid index of first element to be deleted
996 >     */
997 >    private boolean bulkRemoveModified(
998 >        Predicate<? super E> filter, final int beg) {
999 >        final Object[] es = elements;
1000 >        final int capacity = es.length;
1001 >        final int end = tail;
1002 >        final long[] deathRow = nBits(sub(end, beg, capacity));
1003 >        deathRow[0] = 1L;   // set bit 0
1004 >        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1005 >             ; i = 0, to = end, k -= capacity) {
1006 >            for (; i < to; i++)
1007 >                if (filter.test(elementAt(es, i)))
1008 >                    setBit(deathRow, i - k);
1009 >            if (to == end) break;
1010 >        }
1011 >        // a two-finger traversal, with hare i reading, tortoise w writing
1012 >        int w = beg;
1013 >        for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1014 >             ; w = 0) { // w rejoins i on second leg
1015 >            // In this loop, i and w are on the same leg, with i > w
1016 >            for (; i < to; i++)
1017 >                if (isClear(deathRow, i - k))
1018 >                    es[w++] = es[i];
1019 >            if (to == end) break;
1020 >            // In this loop, w is on the first leg, i on the second
1021 >            for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++)
1022 >                if (isClear(deathRow, i - k))
1023 >                    es[w++] = es[i];
1024 >            if (i >= to) {
1025 >                if (w == capacity) w = 0; // "corner" case
1026 >                break;
1027 >            }
1028 >        }
1029 >        if (end != tail) throw new ConcurrentModificationException();
1030 >        circularClear(es, tail = w, end);
1031 >        // checkInvariants();
1032 >        return true;
1033 >    }
1034 >
1035 >    /**
1036 >     * Returns {@code true} if this deque contains the specified element.
1037 >     * More formally, returns {@code true} if and only if this deque contains
1038 >     * at least one element {@code e} such that {@code o.equals(e)}.
1039       *
1040       * @param o object to be checked for containment in this deque
1041 <     * @return <tt>true</tt> if this deque contains the specified element
1041 >     * @return {@code true} if this deque contains the specified element
1042       */
1043      public boolean contains(Object o) {
1044 <        if (o == null)
1045 <            return false;
1046 <        int mask = elements.length - 1;
1047 <        int i = head;
1048 <        E x;
1049 <        while ( (x = elements[i]) != null) {
1050 <            if (o.equals(x))
1051 <                return true;
1052 <            i = (i + 1) & mask;
1044 >        if (o != null) {
1045 >            final Object[] es = elements;
1046 >            for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1047 >                 ; i = 0, to = end) {
1048 >                for (; i < to; i++)
1049 >                    if (o.equals(es[i]))
1050 >                        return true;
1051 >                if (to == end) break;
1052 >            }
1053          }
1054          return false;
1055      }
# Line 669 | Line 1057 | public class ArrayDeque<E> extends Abstr
1057      /**
1058       * Removes a single instance of the specified element from this deque.
1059       * If the deque does not contain the element, it is unchanged.
1060 <     * More formally, removes the first element <tt>e</tt> such that
1061 <     * <tt>o.equals(e)</tt> (if such an element exists).
1062 <     * Returns <tt>true</tt> if this deque contained the specified element
1060 >     * More formally, removes the first element {@code e} such that
1061 >     * {@code o.equals(e)} (if such an element exists).
1062 >     * Returns {@code true} if this deque contained the specified element
1063       * (or equivalently, if this deque changed as a result of the call).
1064       *
1065 <     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
1065 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1066       *
1067       * @param o element to be removed from this deque, if present
1068 <     * @return <tt>true</tt> if this deque contained the specified element
1068 >     * @return {@code true} if this deque contained the specified element
1069       */
1070      public boolean remove(Object o) {
1071          return removeFirstOccurrence(o);
# Line 688 | Line 1076 | public class ArrayDeque<E> extends Abstr
1076       * The deque will be empty after this call returns.
1077       */
1078      public void clear() {
1079 <        int h = head;
1080 <        int t = tail;
1081 <        if (h != t) { // clear all cells
1082 <            head = tail = 0;
1083 <            int i = h;
1084 <            int mask = elements.length - 1;
1085 <            do {
1086 <                elements[i] = null;
1087 <                i = (i + 1) & mask;
1088 <            } while (i != t);
1079 >        circularClear(elements, head, tail);
1080 >        head = tail = 0;
1081 >        // checkInvariants();
1082 >    }
1083 >
1084 >    /**
1085 >     * Nulls out slots starting at array index i, upto index end.
1086 >     * Condition i == end means "empty" - nothing to do.
1087 >     */
1088 >    private static void circularClear(Object[] es, int i, int end) {
1089 >        // assert 0 <= i && i < es.length;
1090 >        // assert 0 <= end && end < es.length;
1091 >        for (int to = (i <= end) ? end : es.length;
1092 >             ; i = 0, to = end) {
1093 >            for (; i < to; i++) es[i] = null;
1094 >            if (to == end) break;
1095          }
1096      }
1097  
# Line 715 | Line 1109 | public class ArrayDeque<E> extends Abstr
1109       * @return an array containing all of the elements in this deque
1110       */
1111      public Object[] toArray() {
1112 <        return copyElements(new Object[size()]);
1112 >        return toArray(Object[].class);
1113 >    }
1114 >
1115 >    private <T> T[] toArray(Class<T[]> klazz) {
1116 >        final Object[] es = elements;
1117 >        final T[] a;
1118 >        final int head = this.head, tail = this.tail, end;
1119 >        if ((end = tail + ((head <= tail) ? 0 : es.length)) >= 0) {
1120 >            // Uses null extension feature of copyOfRange
1121 >            a = Arrays.copyOfRange(es, head, end, klazz);
1122 >        } else {
1123 >            // integer overflow!
1124 >            a = Arrays.copyOfRange(es, 0, end - head, klazz);
1125 >            System.arraycopy(es, head, a, 0, es.length - head);
1126 >        }
1127 >        if (end != tail)
1128 >            System.arraycopy(es, 0, a, es.length - head, tail);
1129 >        return a;
1130      }
1131  
1132      /**
# Line 729 | Line 1140 | public class ArrayDeque<E> extends Abstr
1140       * <p>If this deque fits in the specified array with room to spare
1141       * (i.e., the array has more elements than this deque), the element in
1142       * the array immediately following the end of the deque is set to
1143 <     * <tt>null</tt>.
1143 >     * {@code null}.
1144       *
1145       * <p>Like the {@link #toArray()} method, this method acts as bridge between
1146       * array-based and collection-based APIs.  Further, this method allows
1147       * precise control over the runtime type of the output array, and may,
1148       * under certain circumstances, be used to save allocation costs.
1149       *
1150 <     * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
1150 >     * <p>Suppose {@code x} is a deque known to contain only strings.
1151       * The following code can be used to dump the deque into a newly
1152 <     * allocated array of <tt>String</tt>:
1152 >     * allocated array of {@code String}:
1153       *
1154 <     * <pre>
744 <     *     String[] y = x.toArray(new String[0]);</pre>
1154 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1155       *
1156 <     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
1157 <     * <tt>toArray()</tt>.
1156 >     * Note that {@code toArray(new Object[0])} is identical in function to
1157 >     * {@code toArray()}.
1158       *
1159       * @param a the array into which the elements of the deque are to
1160       *          be stored, if it is big enough; otherwise, a new array of the
# Line 755 | Line 1165 | public class ArrayDeque<E> extends Abstr
1165       *         this deque
1166       * @throws NullPointerException if the specified array is null
1167       */
1168 +    @SuppressWarnings("unchecked")
1169      public <T> T[] toArray(T[] a) {
1170 <        int size = size();
1171 <        if (a.length < size)
1172 <            a = (T[])java.lang.reflect.Array.newInstance(
1173 <                    a.getClass().getComponentType(), size);
1174 <        copyElements(a);
1175 <        if (a.length > size)
1170 >        final int size;
1171 >        if ((size = size()) > a.length)
1172 >            return toArray((Class<T[]>) a.getClass());
1173 >        final Object[] es = elements;
1174 >        for (int i = head, j = 0, len = Math.min(size, es.length - i);
1175 >             ; i = 0, len = tail) {
1176 >            System.arraycopy(es, i, a, j, len);
1177 >            if ((j += len) == size) break;
1178 >        }
1179 >        if (size < a.length)
1180              a[size] = null;
1181          return a;
1182      }
# Line 775 | Line 1190 | public class ArrayDeque<E> extends Abstr
1190       */
1191      public ArrayDeque<E> clone() {
1192          try {
1193 +            @SuppressWarnings("unchecked")
1194              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
1195 <            // These two lines are currently faster than cloning the array:
780 <            result.elements = (E[]) new Object[elements.length];
781 <            System.arraycopy(elements, 0, result.elements, 0, elements.length);
1195 >            result.elements = Arrays.copyOf(elements, elements.length);
1196              return result;
783
1197          } catch (CloneNotSupportedException e) {
1198              throw new AssertionError();
1199          }
1200      }
1201  
789    /**
790     * Appease the serialization gods.
791     */
1202      private static final long serialVersionUID = 2340985798034038923L;
1203  
1204      /**
1205 <     * Serialize this deque.
1205 >     * Saves this deque to a stream (that is, serializes it).
1206       *
1207 <     * @serialData The current size (<tt>int</tt>) of the deque,
1207 >     * @param s the stream
1208 >     * @throws java.io.IOException if an I/O error occurs
1209 >     * @serialData The current size ({@code int}) of the deque,
1210       * followed by all of its elements (each an object reference) in
1211       * first-to-last order.
1212       */
1213 <    private void writeObject(ObjectOutputStream s) throws IOException {
1213 >    private void writeObject(java.io.ObjectOutputStream s)
1214 >            throws java.io.IOException {
1215          s.defaultWriteObject();
1216  
1217          // Write out size
1218          s.writeInt(size());
1219  
1220          // Write out elements in order.
1221 <        int mask = elements.length - 1;
1222 <        for (int i = head; i != tail; i = (i + 1) & mask)
1223 <            s.writeObject(elements[i]);
1221 >        final Object[] es = elements;
1222 >        for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1223 >             ; i = 0, to = end) {
1224 >            for (; i < to; i++)
1225 >                s.writeObject(es[i]);
1226 >            if (to == end) break;
1227 >        }
1228      }
1229  
1230      /**
1231 <     * Deserialize this deque.
1231 >     * Reconstitutes this deque from a stream (that is, deserializes it).
1232 >     * @param s the stream
1233 >     * @throws ClassNotFoundException if the class of a serialized object
1234 >     *         could not be found
1235 >     * @throws java.io.IOException if an I/O error occurs
1236       */
1237 <    private void readObject(ObjectInputStream s)
1238 <            throws IOException, ClassNotFoundException {
1237 >    private void readObject(java.io.ObjectInputStream s)
1238 >            throws java.io.IOException, ClassNotFoundException {
1239          s.defaultReadObject();
1240  
1241          // Read in size and allocate array
1242          int size = s.readInt();
1243 <        allocateElements(size);
1244 <        head = 0;
1245 <        tail = size;
1243 >        jsr166.Platform.checkArray(s, Object[].class, size + 1);
1244 >        elements = new Object[size + 1];
1245 >        this.tail = size;
1246  
1247          // Read in all elements in the proper order.
1248          for (int i = 0; i < size; i++)
1249 <            elements[i] = (E)s.readObject();
1249 >            elements[i] = s.readObject();
1250 >    }
1251  
1252 +    /** debugging */
1253 +    void checkInvariants() {
1254 +        // Use head and tail fields with empty slot at tail strategy.
1255 +        // head == tail disambiguates to "empty".
1256 +        try {
1257 +            int capacity = elements.length;
1258 +            // assert 0 <= head && head < capacity;
1259 +            // assert 0 <= tail && tail < capacity;
1260 +            // assert capacity > 0;
1261 +            // assert size() < capacity;
1262 +            // assert head == tail || elements[head] != null;
1263 +            // assert elements[tail] == null;
1264 +            // assert head == tail || elements[dec(tail, capacity)] != null;
1265 +        } catch (Throwable t) {
1266 +            System.err.printf("head=%d tail=%d capacity=%d%n",
1267 +                              head, tail, elements.length);
1268 +            System.err.printf("elements=%s%n",
1269 +                              Arrays.toString(elements));
1270 +            throw t;
1271 +        }
1272      }
1273 +
1274   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines