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.19 by dl, Fri Sep 16 11:15:41 2005 UTC vs.
Revision 1.98 by jsr166, Sat Oct 29 22:47: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.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  
13   /**
14   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 16 | 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 35 | 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>
# Line 45 | Line 50 | import java.io.*;
50   * Iterator} interfaces.
51   *
52   * <p>This class is a member of the
53 < * <a href="{@docRoot}/../guide/collections/index.html">
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
53 * @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
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.
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.
74 <     */
75 <    private transient int head;
76 <
77 <    /**
78 <     * The index at which the next element would be added to the tail
79 <     * of the deque (via addLast(E), add(E), or push(E)).
80 <     */
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.
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 >        final 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 >        final int oldCapacity = elements.length, minCapacity;
119 >        if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
120 >            if (minCapacity < 0)
121 >                throw new IllegalStateException("Sorry, deque too big");
122 >            return Integer.MAX_VALUE;
123          }
124 <        elements = (E[]) new Object[initialCapacity];
124 >        if (needed > jump)
125 >            return minCapacity;
126 >        return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
127 >            ? oldCapacity + jump
128 >            : MAX_ARRAY_SIZE;
129      }
130  
131      /**
132 <     * Double the capacity of this deque.  Call only when full, i.e.,
133 <     * when head and tail have wrapped around to become equal.
132 >     * Increases the internal storage of this collection, if necessary,
133 >     * to ensure that it can hold at least the given number of elements.
134 >     *
135 >     * @param minCapacity the desired minimum capacity
136 >     * @since TBD
137       */
138 <    private void doubleCapacity() {
139 <        assert head == tail;
140 <        int p = head;
141 <        int n = elements.length;
123 <        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;
138 >    /* public */ 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,
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.
145 >     * Minimizes the internal storage of this collection.
146       *
147 <     * @return its argument
147 >     * @since TBD
148       */
149 <    private <T> T[] copyElements(T[] a) {
150 <        if (head < tail) {
151 <            System.arraycopy(elements, head, a, 0, size());
152 <        } else if (head > tail) {
146 <            int headPortionLen = elements.length - head;
147 <            System.arraycopy(elements, head, a, 0, headPortionLen);
148 <            System.arraycopy(elements, 0, a, headPortionLen, tail);
149 >    /* public */ void trimToSize() {
150 >        if (size < elements.length) {
151 >            elements = toArray();
152 >            head = 0;
153          }
154 <        return a;
154 >        // checkInvariants();
155      }
156  
157      /**
# Line 155 | Line 159 | public class ArrayDeque<E> extends Abstr
159       * sufficient to hold 16 elements.
160       */
161      public ArrayDeque() {
162 <        elements = (E[]) new Object[16];
162 >        elements = new Object[16];
163      }
164  
165      /**
166       * Constructs an empty array deque with an initial capacity
167       * sufficient to hold the specified number of elements.
168       *
169 <     * @param numElements  lower bound on initial capacity of the deque
169 >     * @param numElements lower bound on initial capacity of the deque
170       */
171      public ArrayDeque(int numElements) {
172 <        allocateElements(numElements);
172 >        elements = new Object[numElements];
173      }
174  
175      /**
# Line 179 | Line 183 | public class ArrayDeque<E> extends Abstr
183       * @throws NullPointerException if the specified collection is null
184       */
185      public ArrayDeque(Collection<? extends E> c) {
186 <        allocateElements(c.size());
187 <        addAll(c);
186 >        Object[] es = c.toArray();
187 >        // defend against c.toArray (incorrectly) not returning Object[]
188 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
189 >        if (es.getClass() != Object[].class)
190 >            es = Arrays.copyOf(es, es.length, Object[].class);
191 >        for (Object obj : es)
192 >            Objects.requireNonNull(obj);
193 >        this.elements = es;
194 >        this.size = es.length;
195 >    }
196 >
197 >    /**
198 >     * Increments i, mod modulus.
199 >     * Precondition and postcondition: 0 <= i < modulus.
200 >     */
201 >    static final int inc(int i, int modulus) {
202 >        if (++i >= modulus) i = 0;
203 >        return i;
204 >    }
205 >
206 >    /**
207 >     * Decrements i, mod modulus.
208 >     * Precondition and postcondition: 0 <= i < modulus.
209 >     */
210 >    static final int dec(int i, int modulus) {
211 >        if (--i < 0) i = modulus - 1;
212 >        return i;
213 >    }
214 >
215 >    /**
216 >     * Adds i and j, mod modulus.
217 >     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
218 >     */
219 >    static final int add(int i, int j, int modulus) {
220 >        if ((i += j) - modulus >= 0) i -= modulus;
221 >        return i;
222 >    }
223 >
224 >    /**
225 >     * Returns the array index of the last element.
226 >     * May return invalid index -1 if there are no elements.
227 >     */
228 >    final int tail() {
229 >        return add(head, size - 1, elements.length);
230 >    }
231 >
232 >    /**
233 >     * Returns element at array index i.
234 >     */
235 >    @SuppressWarnings("unchecked")
236 >    private E elementAt(int i) {
237 >        return (E) elements[i];
238 >    }
239 >
240 >    /**
241 >     * A version of elementAt that checks for null elements.
242 >     * This check doesn't catch all possible comodifications,
243 >     * but does catch ones that corrupt traversal.  It's a little
244 >     * surprising that javac allows this abuse of generics.
245 >     */
246 >    static final <E> E nonNullElementAt(Object[] es, int i) {
247 >        @SuppressWarnings("unchecked") E e = (E) es[i];
248 >        if (e == null)
249 >            throw new ConcurrentModificationException();
250 >        return e;
251      }
252  
253      // The main insertion and extraction methods are addFirst,
# Line 194 | Line 261 | public class ArrayDeque<E> extends Abstr
261       * @throws NullPointerException if the specified element is null
262       */
263      public void addFirst(E e) {
264 <        if (e == null)
265 <            throw new NullPointerException();
266 <        elements[head = (head - 1) & (elements.length - 1)] = e;
267 <        if (head == tail)
268 <            doubleCapacity();
264 >        // checkInvariants();
265 >        Objects.requireNonNull(e);
266 >        Object[] es;
267 >        int capacity, h;
268 >        final int s;
269 >        if ((s = size) == (capacity = (es = elements).length)) {
270 >            grow(1);
271 >            capacity = (es = elements).length;
272 >        }
273 >        if ((h = head - 1) < 0) h = capacity - 1;
274 >        es[head = h] = e;
275 >        size = s + 1;
276 >        // checkInvariants();
277      }
278  
279      /**
# Line 210 | Line 285 | public class ArrayDeque<E> extends Abstr
285       * @throws NullPointerException if the specified element is null
286       */
287      public void addLast(E e) {
288 <        if (e == null)
289 <            throw new NullPointerException();
290 <        elements[tail] = e;
291 <        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
292 <            doubleCapacity();
288 >        // checkInvariants();
289 >        Objects.requireNonNull(e);
290 >        Object[] es;
291 >        int capacity;
292 >        final int s;
293 >        if ((s = size) == (capacity = (es = elements).length)) {
294 >            grow(1);
295 >            capacity = (es = elements).length;
296 >        }
297 >        es[add(head, s, capacity)] = e;
298 >        size = s + 1;
299 >        // checkInvariants();
300 >    }
301 >
302 >    /**
303 >     * Adds all of the elements in the specified collection at the end
304 >     * of this deque, as if by calling {@link #addLast} on each one,
305 >     * in the order that they are returned by the collection's
306 >     * iterator.
307 >     *
308 >     * @param c the elements to be inserted into this deque
309 >     * @return {@code true} if this deque changed as a result of the call
310 >     * @throws NullPointerException if the specified collection or any
311 >     *         of its elements are null
312 >     */
313 >    public boolean addAll(Collection<? extends E> c) {
314 >        final int s = size, needed = c.size() - (elements.length - s);
315 >        if (needed > 0)
316 >            grow(needed);
317 >        c.forEach((e) -> addLast(e));
318 >        // checkInvariants();
319 >        return size > s;
320      }
321  
322      /**
323       * Inserts the specified element at the front of this deque.
324       *
325       * @param e the element to add
326 <     * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
326 >     * @return {@code true} (as specified by {@link Deque#offerFirst})
327       * @throws NullPointerException if the specified element is null
328       */
329      public boolean offerFirst(E e) {
# Line 233 | Line 335 | public class ArrayDeque<E> extends Abstr
335       * Inserts the specified element at the end of this deque.
336       *
337       * @param e the element to add
338 <     * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
338 >     * @return {@code true} (as specified by {@link Deque#offerLast})
339       * @throws NullPointerException if the specified element is null
340       */
341      public boolean offerLast(E e) {
# Line 245 | Line 347 | public class ArrayDeque<E> extends Abstr
347       * @throws NoSuchElementException {@inheritDoc}
348       */
349      public E removeFirst() {
350 <        E x = pollFirst();
351 <        if (x == null)
350 >        // checkInvariants();
351 >        E e = pollFirst();
352 >        if (e == null)
353              throw new NoSuchElementException();
354 <        return x;
354 >        return e;
355      }
356  
357      /**
358       * @throws NoSuchElementException {@inheritDoc}
359       */
360      public E removeLast() {
361 <        E x = pollLast();
362 <        if (x == null)
361 >        // checkInvariants();
362 >        E e = pollLast();
363 >        if (e == null)
364              throw new NoSuchElementException();
365 <        return x;
365 >        return e;
366      }
367  
368      public E pollFirst() {
369 <        int h = head;
370 <        E result = elements[h]; // Element is null if deque empty
371 <        if (result == null)
369 >        // checkInvariants();
370 >        int s, h;
371 >        if ((s = size) <= 0)
372              return null;
373 <        elements[h] = null;     // Must null out slot
374 <        head = (h + 1) & (elements.length - 1);
375 <        return result;
373 >        final Object[] elements = this.elements;
374 >        @SuppressWarnings("unchecked") E e = (E) elements[h = head];
375 >        elements[h] = null;
376 >        if (++h >= elements.length) h = 0;
377 >        head = h;
378 >        size = s - 1;
379 >        return e;
380      }
381  
382      public E pollLast() {
383 <        int t = (tail - 1) & (elements.length - 1);
384 <        E result = elements[t];
385 <        if (result == null)
383 >        // checkInvariants();
384 >        final int s, tail;
385 >        if ((s = size) <= 0)
386              return null;
387 <        elements[t] = null;
388 <        tail = t;
389 <        return result;
387 >        final Object[] elements = this.elements;
388 >        @SuppressWarnings("unchecked")
389 >        E e = (E) elements[tail = add(head, s - 1, elements.length)];
390 >        elements[tail] = null;
391 >        size = s - 1;
392 >        return e;
393      }
394  
395      /**
396       * @throws NoSuchElementException {@inheritDoc}
397       */
398      public E getFirst() {
399 <        E x = elements[head];
400 <        if (x == null)
401 <            throw new NoSuchElementException();
291 <        return x;
399 >        // checkInvariants();
400 >        if (size <= 0) throw new NoSuchElementException();
401 >        return elementAt(head);
402      }
403  
404      /**
405       * @throws NoSuchElementException {@inheritDoc}
406       */
407 +    @SuppressWarnings("unchecked")
408      public E getLast() {
409 <        E x = elements[(tail - 1) & (elements.length - 1)];
410 <        if (x == null)
411 <            throw new NoSuchElementException();
412 <        return x;
409 >        // checkInvariants();
410 >        final int s;
411 >        if ((s = size) <= 0) throw new NoSuchElementException();
412 >        final Object[] elements = this.elements;
413 >        return (E) elements[add(head, s - 1, elements.length)];
414      }
415  
416      public E peekFirst() {
417 <        return elements[head]; // elements[head] is null if deque empty
417 >        // checkInvariants();
418 >        return (size <= 0) ? null : elementAt(head);
419      }
420  
421 +    @SuppressWarnings("unchecked")
422      public E peekLast() {
423 <        return elements[(tail - 1) & (elements.length - 1)];
423 >        // checkInvariants();
424 >        final int s;
425 >        if ((s = size) <= 0) return null;
426 >        final Object[] elements = this.elements;
427 >        return (E) elements[add(head, s - 1, elements.length)];
428      }
429  
430      /**
431       * Removes the first occurrence of the specified element in this
432       * deque (when traversing the deque from head to tail).
433       * If the deque does not contain the element, it is unchanged.
434 <     * More formally, removes the first element <tt>e</tt> such that
435 <     * <tt>o.equals(e)</tt> (if such an element exists).
436 <     * Returns <tt>true</tt> if this deque contained the specified element
434 >     * More formally, removes the first element {@code e} such that
435 >     * {@code o.equals(e)} (if such an element exists).
436 >     * Returns {@code true} if this deque contained the specified element
437       * (or equivalently, if this deque changed as a result of the call).
438       *
439       * @param o element to be removed from this deque, if present
440 <     * @return <tt>true</tt> if the deque contained the specified element
440 >     * @return {@code true} if the deque contained the specified element
441       */
442      public boolean removeFirstOccurrence(Object o) {
443 <        if (o == null)
444 <            return false;
445 <        int mask = elements.length - 1;
446 <        int i = head;
447 <        E x;
448 <        while ( (x = elements[i]) != null) {
449 <            if (o.equals(x)) {
450 <                delete(i);
451 <                return true;
443 >        if (o != null) {
444 >            final Object[] elements = this.elements;
445 >            final int capacity = elements.length;
446 >            int i, end, to, todo;
447 >            todo = (end = (i = head) + size)
448 >                - (to = (capacity - end >= 0) ? end : capacity);
449 >            for (;; to = todo, i = 0, todo = 0) {
450 >                for (; i < to; i++)
451 >                    if (o.equals(elements[i])) {
452 >                        delete(i);
453 >                        return true;
454 >                    }
455 >                if (todo == 0) break;
456              }
335            i = (i + 1) & mask;
457          }
458          return false;
459      }
# Line 341 | Line 462 | public class ArrayDeque<E> extends Abstr
462       * Removes the last occurrence of the specified element in this
463       * deque (when traversing the deque from head to tail).
464       * If the deque does not contain the element, it is unchanged.
465 <     * More formally, removes the last element <tt>e</tt> such that
466 <     * <tt>o.equals(e)</tt> (if such an element exists).
467 <     * Returns <tt>true</tt> if this deque contained the specified element
465 >     * More formally, removes the last element {@code e} such that
466 >     * {@code o.equals(e)} (if such an element exists).
467 >     * Returns {@code true} if this deque contained the specified element
468       * (or equivalently, if this deque changed as a result of the call).
469       *
470       * @param o element to be removed from this deque, if present
471 <     * @return <tt>true</tt> if the deque contained the specified element
471 >     * @return {@code true} if the deque contained the specified element
472       */
473      public boolean removeLastOccurrence(Object o) {
474 <        if (o == null)
475 <            return false;
476 <        int mask = elements.length - 1;
477 <        int i = (tail - 1) & mask;
478 <        E x;
479 <        while ( (x = elements[i]) != null) {
480 <            if (o.equals(x)) {
481 <                delete(i);
482 <                return true;
474 >        if (o != null) {
475 >            final Object[] elements = this.elements;
476 >            final int capacity = elements.length;
477 >            int i, to, end, todo;
478 >            todo = (to = ((end = (i = tail()) - size) >= -1) ? end : -1) - end;
479 >            for (;; to = (i = capacity - 1) - todo, todo = 0) {
480 >                for (; i > to; i--)
481 >                    if (o.equals(elements[i])) {
482 >                        delete(i);
483 >                        return true;
484 >                    }
485 >                if (todo == 0) break;
486              }
363            i = (i - 1) & mask;
487          }
488          return false;
489      }
# Line 373 | Line 496 | public class ArrayDeque<E> extends Abstr
496       * <p>This method is equivalent to {@link #addLast}.
497       *
498       * @param e the element to add
499 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
499 >     * @return {@code true} (as specified by {@link Collection#add})
500       * @throws NullPointerException if the specified element is null
501       */
502      public boolean add(E e) {
# Line 387 | Line 510 | public class ArrayDeque<E> extends Abstr
510       * <p>This method is equivalent to {@link #offerLast}.
511       *
512       * @param e the element to add
513 <     * @return <tt>true</tt> (as specified by {@link Queue#offer})
513 >     * @return {@code true} (as specified by {@link Queue#offer})
514       * @throws NullPointerException if the specified element is null
515       */
516      public boolean offer(E e) {
# Line 412 | Line 535 | public class ArrayDeque<E> extends Abstr
535      /**
536       * Retrieves and removes the head of the queue represented by this deque
537       * (in other words, the first element of this deque), or returns
538 <     * <tt>null</tt> if this deque is empty.
538 >     * {@code null} if this deque is empty.
539       *
540       * <p>This method is equivalent to {@link #pollFirst}.
541       *
542       * @return the head of the queue represented by this deque, or
543 <     *         <tt>null</tt> if this deque is empty
543 >     *         {@code null} if this deque is empty
544       */
545      public E poll() {
546          return pollFirst();
# Line 439 | Line 562 | public class ArrayDeque<E> extends Abstr
562  
563      /**
564       * Retrieves, but does not remove, the head of the queue represented by
565 <     * this deque, or returns <tt>null</tt> if this deque is empty.
565 >     * this deque, or returns {@code null} if this deque is empty.
566       *
567       * <p>This method is equivalent to {@link #peekFirst}.
568       *
569       * @return the head of the queue represented by this deque, or
570 <     *         <tt>null</tt> if this deque is empty
570 >     *         {@code null} if this deque is empty
571       */
572      public E peek() {
573          return peekFirst();
# Line 480 | Line 603 | public class ArrayDeque<E> extends Abstr
603      }
604  
605      /**
606 <     * Removes the element at the specified position in the elements array,
607 <     * adjusting head and tail as necessary.  This can result in motion of
608 <     * elements backwards or forwards in the array.
606 >     * Removes the element at the specified position in the elements array.
607 >     * This can result in forward or backwards motion of array elements.
608 >     * We optimize for least element motion.
609       *
610       * <p>This method is called delete rather than remove to emphasize
611       * that its semantics differ from those of {@link List#remove(int)}.
612       *
613       * @return true if elements moved backwards
614       */
615 <    private boolean delete(int i) {
616 <        int mask = elements.length - 1;
617 <
618 <        // Invariant: head <= i < tail mod circularity
619 <        if (((i - head) & mask) >= ((tail - head) & mask))
620 <            throw new ConcurrentModificationException();
621 <
622 <        // Case 1: Deque doesn't wrap
623 <        // Case 2: Deque does wrap and removed element is in the head portion
624 <        if (i >= head) {
625 <            System.arraycopy(elements, head, elements, head + 1, i - head);
626 <            elements[head] = null;
627 <            head = (head + 1) & mask;
615 >    boolean delete(int i) {
616 >        // checkInvariants();
617 >        final Object[] elements = this.elements;
618 >        final int capacity = elements.length;
619 >        final int h = head;
620 >        int front;              // number of elements before to-be-deleted elt
621 >        if ((front = i - h) < 0) front += capacity;
622 >        final int back = size - front - 1; // number of elements after
623 >        if (front < back) {
624 >            // move front elements forwards
625 >            if (h <= i) {
626 >                System.arraycopy(elements, h, elements, h + 1, front);
627 >            } else { // Wrap around
628 >                System.arraycopy(elements, 0, elements, 1, i);
629 >                elements[0] = elements[capacity - 1];
630 >                System.arraycopy(elements, h, elements, h + 1, front - (i + 1));
631 >            }
632 >            elements[h] = null;
633 >            if ((head = (h + 1)) >= capacity) head = 0;
634 >            size--;
635 >            // checkInvariants();
636              return false;
637 +        } else {
638 +            // move back elements backwards
639 +            int tail = tail();
640 +            if (i <= tail) {
641 +                System.arraycopy(elements, i + 1, elements, i, back);
642 +            } else { // Wrap around
643 +                int firstLeg = capacity - (i + 1);
644 +                System.arraycopy(elements, i + 1, elements, i, firstLeg);
645 +                elements[capacity - 1] = elements[0];
646 +                System.arraycopy(elements, 1, elements, 0, back - firstLeg - 1);
647 +            }
648 +            elements[tail] = null;
649 +            size--;
650 +            // checkInvariants();
651 +            return true;
652          }
507
508        // Case 3: Deque wraps and removed element is in the tail portion
509        tail--;
510        System.arraycopy(elements, i + 1, elements, i, tail - i);
511        elements[tail] = null;
512        return true;
653      }
654  
655      // *** Collection Methods ***
# Line 520 | Line 660 | public class ArrayDeque<E> extends Abstr
660       * @return the number of elements in this deque
661       */
662      public int size() {
663 <        return (tail - head) & (elements.length - 1);
663 >        return size;
664      }
665  
666      /**
667 <     * Returns <tt>true</tt> if this deque contains no elements.
667 >     * Returns {@code true} if this deque contains no elements.
668       *
669 <     * @return <tt>true</tt> if this deque contains no elements
669 >     * @return {@code true} if this deque contains no elements
670       */
671      public boolean isEmpty() {
672 <        return head == tail;
672 >        return size == 0;
673      }
674  
675      /**
# Line 549 | Line 689 | public class ArrayDeque<E> extends Abstr
689      }
690  
691      private class DeqIterator implements Iterator<E> {
692 <        /**
693 <         * Index of element to be returned by subsequent call to next.
554 <         */
555 <        private int cursor = head;
692 >        /** Index of element to be returned by subsequent call to next. */
693 >        int cursor;
694  
695 <        /**
696 <         * Tail recorded at construction (also in remove), to stop
559 <         * iterator and also to check for comodification.
560 <         */
561 <        private int fence = tail;
695 >        /** Number of elements yet to be returned. */
696 >        int remaining = size;
697  
698          /**
699           * Index of element returned by most recent call to next.
700           * Reset to -1 if element is deleted by a call to remove.
701           */
702 <        private int lastRet = -1;
702 >        int lastRet = -1;
703 >
704 >        DeqIterator() { cursor = head; }
705  
706 <        public boolean hasNext() {
707 <            return cursor != fence;
706 >        public final boolean hasNext() {
707 >            return remaining > 0;
708          }
709  
710          public E next() {
711 <            E result;
575 <            if (cursor == fence)
711 >            if (remaining <= 0)
712                  throw new NoSuchElementException();
713 <            // This check doesn't catch all possible comodifications,
714 <            // but does catch the ones that corrupt traversal
579 <            if (tail != fence || (result = elements[cursor]) == null)
580 <                throw new ConcurrentModificationException();
713 >            final Object[] elements = ArrayDeque.this.elements;
714 >            E e = nonNullElementAt(elements, cursor);
715              lastRet = cursor;
716 <            cursor = (cursor + 1) & (elements.length - 1);
717 <            return result;
716 >            if (++cursor >= elements.length) cursor = 0;
717 >            remaining--;
718 >            return e;
719 >        }
720 >
721 >        void postDelete(boolean leftShifted) {
722 >            if (leftShifted)
723 >                if (--cursor < 0) cursor = elements.length - 1;
724          }
725  
726 <        public void remove() {
726 >        public final void remove() {
727              if (lastRet < 0)
728                  throw new IllegalStateException();
729 <            if (delete(lastRet)) // if left-shifted, undo increment in next()
590 <                cursor = (cursor - 1) & (elements.length - 1);
729 >            postDelete(delete(lastRet));
730              lastRet = -1;
731 <            fence = tail;
731 >        }
732 >
733 >        public void forEachRemaining(Consumer<? super E> action) {
734 >            Objects.requireNonNull(action);
735 >            final int k;
736 >            if ((k = remaining) > 0) {
737 >                remaining = 0;
738 >                ArrayDeque.forEachRemaining(action, elements, cursor, k);
739 >                if ((lastRet = cursor + k - 1) >= elements.length)
740 >                    lastRet -= elements.length;
741 >            }
742          }
743      }
744  
745 +    private class DescendingIterator extends DeqIterator {
746 +        DescendingIterator() { cursor = tail(); }
747  
748 <    private class DescendingIterator implements Iterator<E> {
749 <        /*
750 <         * This class is nearly a mirror-image of DeqIterator, using
751 <         * (tail-1) instead of head for initial cursor, (head-1)
752 <         * instead of tail for fence, and elements.length instead of -1
753 <         * for sentinel. It shares the same structure, but not many
754 <         * actual lines of code.
755 <         */
756 <        private int cursor = (tail - 1) & (elements.length - 1);
757 <        private int fence =  (head - 1) & (elements.length - 1);
607 <        private int lastRet = elements.length;
748 >        public final E next() {
749 >            if (remaining <= 0)
750 >                throw new NoSuchElementException();
751 >            final Object[] elements = ArrayDeque.this.elements;
752 >            E e = nonNullElementAt(elements, cursor);
753 >            lastRet = cursor;
754 >            if (--cursor < 0) cursor = elements.length - 1;
755 >            remaining--;
756 >            return e;
757 >        }
758  
759 <        public boolean hasNext() {
760 <            return cursor != fence;
759 >        void postDelete(boolean leftShifted) {
760 >            if (!leftShifted)
761 >                if (++cursor >= elements.length) cursor = 0;
762          }
763  
764 <        public E next() {
765 <            E result;
766 <            if (cursor == fence)
767 <                throw new NoSuchElementException();
768 <            if (((head - 1) & (elements.length - 1)) != fence ||
769 <                (result = elements[cursor]) == null)
770 <                throw new ConcurrentModificationException();
771 <            lastRet = cursor;
772 <            cursor = (cursor - 1) & (elements.length - 1);
773 <            return result;
764 >        public final void forEachRemaining(Consumer<? super E> action) {
765 >            Objects.requireNonNull(action);
766 >            final int k;
767 >            if ((k = remaining) > 0) {
768 >                remaining = 0;
769 >                final Object[] elements = ArrayDeque.this.elements;
770 >                int i, end, to, todo;
771 >                todo = (to = ((end = (i = cursor) - k) >= -1) ? end : -1) - end;
772 >                for (;; to = (i = elements.length - 1) - todo, todo = 0) {
773 >                    for (; i > to; i--)
774 >                        action.accept(nonNullElementAt(elements, i));
775 >                    if (todo == 0) break;
776 >                }
777 >                if ((lastRet = cursor - (k - 1)) < 0)
778 >                    lastRet += elements.length;
779 >            }
780          }
781 +    }
782  
783 <        public void remove() {
784 <            if (lastRet >= elements.length)
785 <                throw new IllegalStateException();
786 <            if (!delete(lastRet))
787 <                cursor = (cursor + 1) & (elements.length - 1);
788 <            lastRet = elements.length;
789 <            fence = (head - 1) & (elements.length - 1);
783 >    /**
784 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
785 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
786 >     * deque.
787 >     *
788 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
789 >     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
790 >     * {@link Spliterator#NONNULL}.  Overriding implementations should document
791 >     * the reporting of additional characteristic values.
792 >     *
793 >     * @return a {@code Spliterator} over the elements in this deque
794 >     * @since 1.8
795 >     */
796 >    public Spliterator<E> spliterator() {
797 >        return new ArrayDequeSpliterator();
798 >    }
799 >
800 >    final class ArrayDequeSpliterator implements Spliterator<E> {
801 >        private int cursor;
802 >        private int remaining; // -1 until late-binding first use
803 >
804 >        /** Constructs late-binding spliterator over all elements. */
805 >        ArrayDequeSpliterator() {
806 >            this.remaining = -1;
807 >        }
808 >
809 >        /** Constructs spliterator over the given slice. */
810 >        ArrayDequeSpliterator(int cursor, int count) {
811 >            this.cursor = cursor;
812 >            this.remaining = count;
813 >        }
814 >
815 >        /** Ensures late-binding initialization; then returns remaining. */
816 >        private int remaining() {
817 >            if (remaining < 0) {
818 >                cursor = head;
819 >                remaining = size;
820 >            }
821 >            return remaining;
822 >        }
823 >
824 >        public ArrayDequeSpliterator trySplit() {
825 >            final int mid;
826 >            if ((mid = remaining() >> 1) > 0) {
827 >                int oldCursor = cursor;
828 >                cursor = add(cursor, mid, elements.length);
829 >                remaining -= mid;
830 >                return new ArrayDequeSpliterator(oldCursor, mid);
831 >            }
832 >            return null;
833 >        }
834 >
835 >        public void forEachRemaining(Consumer<? super E> action) {
836 >            Objects.requireNonNull(action);
837 >            final int k = remaining(); // side effect!
838 >            remaining = 0;
839 >            ArrayDeque.forEachRemaining(action, elements, cursor, k);
840 >        }
841 >
842 >        public boolean tryAdvance(Consumer<? super E> action) {
843 >            Objects.requireNonNull(action);
844 >            final int k;
845 >            if ((k = remaining()) <= 0)
846 >                return false;
847 >            action.accept(nonNullElementAt(elements, cursor));
848 >            if (++cursor >= elements.length) cursor = 0;
849 >            remaining = k - 1;
850 >            return true;
851 >        }
852 >
853 >        public long estimateSize() {
854 >            return remaining();
855 >        }
856 >
857 >        public int characteristics() {
858 >            return Spliterator.NONNULL
859 >                | Spliterator.ORDERED
860 >                | Spliterator.SIZED
861 >                | Spliterator.SUBSIZED;
862 >        }
863 >    }
864 >
865 >    @SuppressWarnings("unchecked")
866 >    public void forEach(Consumer<? super E> action) {
867 >        Objects.requireNonNull(action);
868 >        final Object[] elements = this.elements;
869 >        final int capacity = elements.length;
870 >        int i, end, to, todo;
871 >        todo = (end = (i = head) + size)
872 >            - (to = (capacity - end >= 0) ? end : capacity);
873 >        for (;; to = todo, i = 0, todo = 0) {
874 >            for (; i < to; i++)
875 >                action.accept((E) elements[i]);
876 >            if (todo == 0) break;
877 >        }
878 >        // checkInvariants();
879 >    }
880 >
881 >    /**
882 >     * Calls action on remaining elements, starting at index i and
883 >     * traversing in ascending order.  A variant of forEach that also
884 >     * checks for concurrent modification, for use in iterators.
885 >     */
886 >    static <E> void forEachRemaining(
887 >        Consumer<? super E> action, Object[] es, int i, int remaining) {
888 >        final int capacity = es.length;
889 >        int end, to, todo;
890 >        todo = (end = i + remaining)
891 >            - (to = (capacity - end >= 0) ? end : capacity);
892 >        for (;; to = todo, i = 0, todo = 0) {
893 >            for (; i < to; i++)
894 >                action.accept(nonNullElementAt(es, i));
895 >            if (todo == 0) break;
896 >        }
897 >    }
898 >
899 >    /**
900 >     * Replaces each element of this deque with the result of applying the
901 >     * operator to that element, as specified by {@link List#replaceAll}.
902 >     *
903 >     * @param operator the operator to apply to each element
904 >     * @since TBD
905 >     */
906 >    /* public */ void replaceAll(UnaryOperator<E> operator) {
907 >        Objects.requireNonNull(operator);
908 >        final Object[] elements = this.elements;
909 >        final int capacity = elements.length;
910 >        int i, end, to, todo;
911 >        todo = (end = (i = head) + size)
912 >            - (to = (capacity - end >= 0) ? end : capacity);
913 >        for (;; to = todo, i = 0, todo = 0) {
914 >            for (; i < to; i++)
915 >                elements[i] = operator.apply(elementAt(i));
916 >            if (todo == 0) break;
917 >        }
918 >        // checkInvariants();
919 >    }
920 >
921 >    /**
922 >     * @throws NullPointerException {@inheritDoc}
923 >     */
924 >    public boolean removeIf(Predicate<? super E> filter) {
925 >        Objects.requireNonNull(filter);
926 >        return bulkRemove(filter);
927 >    }
928 >
929 >    /**
930 >     * @throws NullPointerException {@inheritDoc}
931 >     */
932 >    public boolean removeAll(Collection<?> c) {
933 >        Objects.requireNonNull(c);
934 >        return bulkRemove(e -> c.contains(e));
935 >    }
936 >
937 >    /**
938 >     * @throws NullPointerException {@inheritDoc}
939 >     */
940 >    public boolean retainAll(Collection<?> c) {
941 >        Objects.requireNonNull(c);
942 >        return bulkRemove(e -> !c.contains(e));
943 >    }
944 >
945 >    /** Implementation of bulk remove methods. */
946 >    private boolean bulkRemove(Predicate<? super E> filter) {
947 >        // checkInvariants();
948 >        final Object[] elements = this.elements;
949 >        final int capacity = elements.length;
950 >        int i = head, j = i, remaining = size, deleted = 0;
951 >        try {
952 >            for (; remaining > 0; remaining--) {
953 >                @SuppressWarnings("unchecked") E e = (E) elements[i];
954 >                if (filter.test(e))
955 >                    deleted++;
956 >                else {
957 >                    if (j != i)
958 >                        elements[j] = e;
959 >                    if (++j >= capacity) j = 0;
960 >                }
961 >                if (++i >= capacity) i = 0;
962 >            }
963 >            return deleted > 0;
964 >        } catch (Throwable ex) {
965 >            if (deleted > 0)
966 >                for (; remaining > 0; remaining--) {
967 >                    elements[j] = elements[i];
968 >                    if (++i >= capacity) i = 0;
969 >                    if (++j >= capacity) j = 0;
970 >                }
971 >            throw ex;
972 >        } finally {
973 >            size -= deleted;
974 >            clearSlice(elements, j, deleted);
975 >            // checkInvariants();
976          }
977      }
978  
979      /**
980 <     * Returns <tt>true</tt> if this deque contains the specified element.
981 <     * More formally, returns <tt>true</tt> if and only if this deque contains
982 <     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
980 >     * Returns {@code true} if this deque contains the specified element.
981 >     * More formally, returns {@code true} if and only if this deque contains
982 >     * at least one element {@code e} such that {@code o.equals(e)}.
983       *
984       * @param o object to be checked for containment in this deque
985 <     * @return <tt>true</tt> if this deque contains the specified element
985 >     * @return {@code true} if this deque contains the specified element
986       */
987      public boolean contains(Object o) {
988 <        if (o == null)
989 <            return false;
990 <        int mask = elements.length - 1;
991 <        int i = head;
992 <        E x;
993 <        while ( (x = elements[i]) != null) {
994 <            if (o.equals(x))
995 <                return true;
996 <            i = (i + 1) & mask;
988 >        if (o != null) {
989 >            final Object[] elements = this.elements;
990 >            final int capacity = elements.length;
991 >            int i, end, to, todo;
992 >            todo = (end = (i = head) + size)
993 >                - (to = (capacity - end >= 0) ? end : capacity);
994 >            for (;; to = todo, i = 0, todo = 0) {
995 >                for (; i < to; i++)
996 >                    if (o.equals(elements[i]))
997 >                        return true;
998 >                if (todo == 0) break;
999 >            }
1000          }
1001          return false;
1002      }
# Line 657 | Line 1004 | public class ArrayDeque<E> extends Abstr
1004      /**
1005       * Removes a single instance of the specified element from this deque.
1006       * If the deque does not contain the element, it is unchanged.
1007 <     * More formally, removes the first element <tt>e</tt> such that
1008 <     * <tt>o.equals(e)</tt> (if such an element exists).
1009 <     * Returns <tt>true</tt> if this deque contained the specified element
1007 >     * More formally, removes the first element {@code e} such that
1008 >     * {@code o.equals(e)} (if such an element exists).
1009 >     * Returns {@code true} if this deque contained the specified element
1010       * (or equivalently, if this deque changed as a result of the call).
1011       *
1012 <     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
1012 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1013       *
1014       * @param o element to be removed from this deque, if present
1015 <     * @return <tt>true</tt> if this deque contained the specified element
1015 >     * @return {@code true} if this deque contained the specified element
1016       */
1017      public boolean remove(Object o) {
1018          return removeFirstOccurrence(o);
# Line 676 | Line 1023 | public class ArrayDeque<E> extends Abstr
1023       * The deque will be empty after this call returns.
1024       */
1025      public void clear() {
1026 <        int h = head;
1027 <        int t = tail;
1028 <        if (h != t) { // clear all cells
1029 <            head = tail = 0;
1030 <            int i = h;
1031 <            int mask = elements.length - 1;
1032 <            do {
1033 <                elements[i] = null;
1034 <                i = (i + 1) & mask;
1035 <            } while (i != t);
1036 <        }
1026 >        clearSlice(elements, head, size);
1027 >        size = head = 0;
1028 >        // checkInvariants();
1029 >    }
1030 >
1031 >    /**
1032 >     * Nulls out count elements, starting at array index from.
1033 >     */
1034 >    private static void clearSlice(Object[] es, int from, int count) {
1035 >        final int capacity = es.length, end = from + count;
1036 >        final int leg = (capacity - end >= 0) ? end : capacity;
1037 >        Arrays.fill(es, from, leg, null);
1038 >        if (leg != end)
1039 >            Arrays.fill(es, 0, end - capacity, null);
1040      }
1041  
1042      /**
# Line 703 | Line 1053 | public class ArrayDeque<E> extends Abstr
1053       * @return an array containing all of the elements in this deque
1054       */
1055      public Object[] toArray() {
1056 <        return copyElements(new Object[size()]);
1056 >        return toArray(Object[].class);
1057 >    }
1058 >
1059 >    private <T> T[] toArray(Class<T[]> klazz) {
1060 >        final Object[] elements = this.elements;
1061 >        final int capacity = elements.length;
1062 >        final int head = this.head, end = head + size;
1063 >        final T[] a;
1064 >        if (end >= 0) {
1065 >            a = Arrays.copyOfRange(elements, head, end, klazz);
1066 >        } else {
1067 >            // integer overflow!
1068 >            a = Arrays.copyOfRange(elements, 0, size, klazz);
1069 >            System.arraycopy(elements, head, a, 0, capacity - head);
1070 >        }
1071 >        if (end - capacity > 0)
1072 >            System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1073 >        return a;
1074      }
1075  
1076      /**
# Line 717 | Line 1084 | public class ArrayDeque<E> extends Abstr
1084       * <p>If this deque fits in the specified array with room to spare
1085       * (i.e., the array has more elements than this deque), the element in
1086       * the array immediately following the end of the deque is set to
1087 <     * <tt>null</tt>.
1087 >     * {@code null}.
1088       *
1089       * <p>Like the {@link #toArray()} method, this method acts as bridge between
1090       * array-based and collection-based APIs.  Further, this method allows
1091       * precise control over the runtime type of the output array, and may,
1092       * under certain circumstances, be used to save allocation costs.
1093       *
1094 <     * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
1094 >     * <p>Suppose {@code x} is a deque known to contain only strings.
1095       * The following code can be used to dump the deque into a newly
1096 <     * allocated array of <tt>String</tt>:
1096 >     * allocated array of {@code String}:
1097       *
1098 <     * <pre>
732 <     *     String[] y = x.toArray(new String[0]);</pre>
1098 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1099       *
1100 <     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
1101 <     * <tt>toArray()</tt>.
1100 >     * Note that {@code toArray(new Object[0])} is identical in function to
1101 >     * {@code toArray()}.
1102       *
1103       * @param a the array into which the elements of the deque are to
1104       *          be stored, if it is big enough; otherwise, a new array of the
# Line 743 | Line 1109 | public class ArrayDeque<E> extends Abstr
1109       *         this deque
1110       * @throws NullPointerException if the specified array is null
1111       */
1112 +    @SuppressWarnings("unchecked")
1113      public <T> T[] toArray(T[] a) {
1114 <        int size = size();
1115 <        if (a.length < size)
1116 <            a = (T[])java.lang.reflect.Array.newInstance(
1117 <                    a.getClass().getComponentType(), size);
1118 <        copyElements(a);
1119 <        if (a.length > size)
1114 >        final int size = this.size;
1115 >        if (size > a.length)
1116 >            return toArray((Class<T[]>) a.getClass());
1117 >        final Object[] elements = this.elements;
1118 >        final int capacity = elements.length;
1119 >        final int head = this.head, end = head + size;
1120 >        final int front = (capacity - end >= 0) ? size : capacity - head;
1121 >        System.arraycopy(elements, head, a, 0, front);
1122 >        if (front != size)
1123 >            System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1124 >        if (size < a.length)
1125              a[size] = null;
1126          return a;
1127      }
# Line 763 | Line 1135 | public class ArrayDeque<E> extends Abstr
1135       */
1136      public ArrayDeque<E> clone() {
1137          try {
1138 +            @SuppressWarnings("unchecked")
1139              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
1140 <            // These two lines are currently faster than cloning the array:
768 <            result.elements = (E[]) new Object[elements.length];
769 <            System.arraycopy(elements, 0, result.elements, 0, elements.length);
1140 >            result.elements = Arrays.copyOf(elements, elements.length);
1141              return result;
771
1142          } catch (CloneNotSupportedException e) {
1143              throw new AssertionError();
1144          }
1145      }
1146  
777    /**
778     * Appease the serialization gods.
779     */
1147      private static final long serialVersionUID = 2340985798034038923L;
1148  
1149      /**
1150 <     * Serialize this deque.
1150 >     * Saves this deque to a stream (that is, serializes it).
1151       *
1152 <     * @serialData The current size (<tt>int</tt>) of the deque,
1152 >     * @param s the stream
1153 >     * @throws java.io.IOException if an I/O error occurs
1154 >     * @serialData The current size ({@code int}) of the deque,
1155       * followed by all of its elements (each an object reference) in
1156       * first-to-last order.
1157       */
1158 <    private void writeObject(ObjectOutputStream s) throws IOException {
1158 >    private void writeObject(java.io.ObjectOutputStream s)
1159 >            throws java.io.IOException {
1160          s.defaultWriteObject();
1161  
1162          // Write out size
1163 <        s.writeInt(size());
1163 >        s.writeInt(size);
1164  
1165          // Write out elements in order.
1166 <        int mask = elements.length - 1;
1167 <        for (int i = head; i != tail; i = (i + 1) & mask)
1168 <            s.writeObject(elements[i]);
1166 >        final Object[] elements = this.elements;
1167 >        final int capacity = elements.length;
1168 >        int i, end, to, todo;
1169 >        todo = (end = (i = head) + size)
1170 >            - (to = (capacity - end >= 0) ? end : capacity);
1171 >        for (;; to = todo, i = 0, todo = 0) {
1172 >            for (; i < to; i++)
1173 >                s.writeObject(elements[i]);
1174 >            if (todo == 0) break;
1175 >        }
1176      }
1177  
1178      /**
1179 <     * Deserialize this deque.
1179 >     * Reconstitutes this deque from a stream (that is, deserializes it).
1180 >     * @param s the stream
1181 >     * @throws ClassNotFoundException if the class of a serialized object
1182 >     *         could not be found
1183 >     * @throws java.io.IOException if an I/O error occurs
1184       */
1185 <    private void readObject(ObjectInputStream s)
1186 <            throws IOException, ClassNotFoundException {
1185 >    private void readObject(java.io.ObjectInputStream s)
1186 >            throws java.io.IOException, ClassNotFoundException {
1187          s.defaultReadObject();
1188  
1189          // Read in size and allocate array
1190 <        int size = s.readInt();
810 <        allocateElements(size);
811 <        head = 0;
812 <        tail = size;
1190 >        elements = new Object[size = s.readInt()];
1191  
1192          // Read in all elements in the proper order.
1193          for (int i = 0; i < size; i++)
1194 <            elements[i] = (E)s.readObject();
1194 >            elements[i] = s.readObject();
1195 >    }
1196  
1197 +    /** debugging */
1198 +    void checkInvariants() {
1199 +        try {
1200 +            int capacity = elements.length;
1201 +            // assert size >= 0 && size <= capacity;
1202 +            // assert head >= 0;
1203 +            // assert capacity == 0 || head < capacity;
1204 +            // assert size == 0 || elements[head] != null;
1205 +            // assert size == 0 || elements[tail()] != null;
1206 +            // assert size == capacity || elements[dec(head, capacity)] == null;
1207 +            // assert size == capacity || elements[inc(tail(), capacity)] == null;
1208 +        } catch (Throwable t) {
1209 +            System.err.printf("head=%d size=%d capacity=%d%n",
1210 +                              head, size, elements.length);
1211 +            System.err.printf("elements=%s%n",
1212 +                              Arrays.toString(elements));
1213 +            throw t;
1214 +        }
1215      }
1216 +
1217   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines