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.21 by dl, Fri Sep 16 23:17:05 2005 UTC vs.
Revision 1.66 by jsr166, Sat Feb 28 22:16:45 2015 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  
11   /**
12   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 16 | Line 17 | import java.io.*;
17   * {@link Stack} when used as a stack, and faster than {@link LinkedList}
18   * when used as a queue.
19   *
20 < * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
21 < * Exceptions include {@link #remove(Object) remove}, {@link
22 < * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
23 < * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
24 < * iterator.remove()}, and the bulk operations, all of which run in linear
25 < * time.
20 > * <p>Most {@code ArrayDeque} operations run in amortized constant time.
21 > * Exceptions include
22 > * {@link #remove(Object) remove},
23 > * {@link #removeFirstOccurrence removeFirstOccurrence},
24 > * {@link #removeLastOccurrence removeLastOccurrence},
25 > * {@link #contains contains},
26 > * {@link #iterator iterator.remove()},
27 > * and the bulk operations, all of which run in linear time.
28   *
29 < * <p>The iterators returned by this class's <tt>iterator</tt> method are
30 < * <i>fail-fast</i>: If the deque is modified at any time after the iterator
31 < * is created, in any way except through the iterator's own <tt>remove</tt>
32 < * method, the iterator will generally throw a {@link
29 > * <p>The iterators returned by this class's {@link #iterator() iterator}
30 > * method are <em>fail-fast</em>: If the deque is modified at any time after
31 > * the iterator is created, in any way except through the iterator's own
32 > * {@code remove} method, the iterator will generally throw a {@link
33   * ConcurrentModificationException}.  Thus, in the face of concurrent
34   * modification, the iterator fails quickly and cleanly, rather than risking
35   * arbitrary, non-deterministic behavior at an undetermined time in the
# Line 35 | Line 38 | import java.io.*;
38   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
39   * as it is, generally speaking, impossible to make any hard guarantees in the
40   * presence of unsynchronized concurrent modification.  Fail-fast iterators
41 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
41 > * throw {@code ConcurrentModificationException} on a best-effort basis.
42   * Therefore, it would be wrong to write a program that depended on this
43   * exception for its correctness: <i>the fail-fast behavior of iterators
44   * should be used only to detect bugs.</i>
# Line 45 | Line 48 | import java.io.*;
48   * Iterator} interfaces.
49   *
50   * <p>This class is a member of the
51 < * <a href="{@docRoot}/../guide/collections/index.html">
51 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
52   * Java Collections Framework</a>.
53   *
54   * @author  Josh Bloch and Doug Lea
55   * @since   1.6
56 < * @param <E> the type of elements held in this collection
56 > * @param <E> the type of elements held in this deque
57   */
58   public class ArrayDeque<E> extends AbstractCollection<E>
59                             implements Deque<E>, Cloneable, Serializable
# Line 65 | Line 68 | public class ArrayDeque<E> extends Abstr
68       * other.  We also guarantee that all array cells not holding
69       * deque elements are always null.
70       */
71 <    private transient E[] elements;
71 >    transient Object[] elements; // non-private to simplify nested class access
72  
73      /**
74       * The index of the element at the head of the deque (which is the
75       * element that would be removed by remove() or pop()); or an
76       * arbitrary number equal to tail if the deque is empty.
77       */
78 <    private transient int head;
78 >    transient int head;
79  
80      /**
81       * The index at which the next element would be added to the tail
82       * of the deque (via addLast(E), add(E), or push(E)).
83       */
84 <    private transient int tail;
84 >    transient int tail;
85  
86      /**
87       * The minimum capacity that we'll use for a newly created deque.
# Line 89 | Line 92 | public class ArrayDeque<E> extends Abstr
92      // ******  Array allocation and resizing utilities ******
93  
94      /**
95 <     * Allocate empty array to hold the given number of elements.
95 >     * Allocates empty array to hold the given number of elements.
96       *
97       * @param numElements  the number of elements to hold
98       */
# Line 109 | Line 112 | public class ArrayDeque<E> extends Abstr
112              if (initialCapacity < 0)   // Too many elements, must back off
113                  initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
114          }
115 <        elements = (E[]) new Object[initialCapacity];
115 >        elements = new Object[initialCapacity];
116      }
117  
118      /**
119 <     * Double the capacity of this deque.  Call only when full, i.e.,
119 >     * Doubles the capacity of this deque.  Call only when full, i.e.,
120       * when head and tail have wrapped around to become equal.
121       */
122      private void doubleCapacity() {
# Line 127 | Line 130 | public class ArrayDeque<E> extends Abstr
130          Object[] a = new Object[newCapacity];
131          System.arraycopy(elements, p, a, 0, r);
132          System.arraycopy(elements, 0, a, r, p);
133 <        elements = (E[])a;
133 >        elements = a;
134          head = 0;
135          tail = n;
136      }
137  
138      /**
136     * 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.
139     *
140     * @return its argument
141     */
142    private <T> T[] copyElements(T[] a) {
143        if (head < tail) {
144            System.arraycopy(elements, head, a, 0, size());
145        } 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        }
150        return a;
151    }
152
153    /**
139       * Constructs an empty array deque with an initial capacity
140       * sufficient to hold 16 elements.
141       */
142      public ArrayDeque() {
143 <        elements = (E[]) new Object[16];
143 >        elements = new Object[16];
144      }
145  
146      /**
# Line 221 | Line 206 | public class ArrayDeque<E> extends Abstr
206       * Inserts the specified element at the front of this deque.
207       *
208       * @param e the element to add
209 <     * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
209 >     * @return {@code true} (as specified by {@link Deque#offerFirst})
210       * @throws NullPointerException if the specified element is null
211       */
212      public boolean offerFirst(E e) {
# Line 233 | Line 218 | public class ArrayDeque<E> extends Abstr
218       * Inserts the specified element at the end of this deque.
219       *
220       * @param e the element to add
221 <     * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
221 >     * @return {@code true} (as specified by {@link Deque#offerLast})
222       * @throws NullPointerException if the specified element is null
223       */
224      public boolean offerLast(E e) {
# Line 262 | Line 247 | public class ArrayDeque<E> extends Abstr
247      }
248  
249      public E pollFirst() {
250 <        int h = head;
251 <        E result = elements[h]; // Element is null if deque empty
252 <        if (result == null)
253 <            return null;
254 <        elements[h] = null;     // Must null out slot
255 <        head = (h + 1) & (elements.length - 1);
250 >        final Object[] elements = this.elements;
251 >        final int h = head;
252 >        @SuppressWarnings("unchecked")
253 >        E result = (E) elements[h];
254 >        // Element is null if deque empty
255 >        if (result != null) {
256 >            elements[h] = null; // Must null out slot
257 >            head = (h + 1) & (elements.length - 1);
258 >        }
259          return result;
260      }
261  
262      public E pollLast() {
263 <        int t = (tail - 1) & (elements.length - 1);
264 <        E result = elements[t];
265 <        if (result == null)
266 <            return null;
267 <        elements[t] = null;
268 <        tail = t;
263 >        final Object[] elements = this.elements;
264 >        final int t = (tail - 1) & (elements.length - 1);
265 >        @SuppressWarnings("unchecked")
266 >        E result = (E) elements[t];
267 >        if (result != null) {
268 >            elements[t] = null;
269 >            tail = t;
270 >        }
271          return result;
272      }
273  
# Line 285 | Line 275 | public class ArrayDeque<E> extends Abstr
275       * @throws NoSuchElementException {@inheritDoc}
276       */
277      public E getFirst() {
278 <        E x = elements[head];
279 <        if (x == null)
278 >        @SuppressWarnings("unchecked")
279 >        E result = (E) elements[head];
280 >        if (result == null)
281              throw new NoSuchElementException();
282 <        return x;
282 >        return result;
283      }
284  
285      /**
286       * @throws NoSuchElementException {@inheritDoc}
287       */
288      public E getLast() {
289 <        E x = elements[(tail - 1) & (elements.length - 1)];
290 <        if (x == null)
289 >        @SuppressWarnings("unchecked")
290 >        E result = (E) elements[(tail - 1) & (elements.length - 1)];
291 >        if (result == null)
292              throw new NoSuchElementException();
293 <        return x;
293 >        return result;
294      }
295  
296 +    @SuppressWarnings("unchecked")
297      public E peekFirst() {
298 <        return elements[head]; // elements[head] is null if deque empty
298 >        // elements[head] is null if deque empty
299 >        return (E) elements[head];
300      }
301  
302 +    @SuppressWarnings("unchecked")
303      public E peekLast() {
304 <        return elements[(tail - 1) & (elements.length - 1)];
304 >        return (E) elements[(tail - 1) & (elements.length - 1)];
305      }
306  
307      /**
308       * Removes the first occurrence of the specified element in this
309       * deque (when traversing the deque from head to tail).
310       * If the deque does not contain the element, it is unchanged.
311 <     * More formally, removes the first element <tt>e</tt> such that
312 <     * <tt>o.equals(e)</tt> (if such an element exists).
313 <     * Returns <tt>true</tt> if this deque contained the specified element
311 >     * More formally, removes the first element {@code e} such that
312 >     * {@code o.equals(e)} (if such an element exists).
313 >     * Returns {@code true} if this deque contained the specified element
314       * (or equivalently, if this deque changed as a result of the call).
315       *
316       * @param o element to be removed from this deque, if present
317 <     * @return <tt>true</tt> if the deque contained the specified element
317 >     * @return {@code true} if the deque contained the specified element
318       */
319      public boolean removeFirstOccurrence(Object o) {
320 <        if (o == null)
321 <            return false;
322 <        int mask = elements.length - 1;
323 <        int i = head;
324 <        E x;
325 <        while ( (x = elements[i]) != null) {
326 <            if (o.equals(x)) {
327 <                delete(i);
333 <                return true;
320 >        if (o != null) {
321 >            int mask = elements.length - 1;
322 >            int i = head;
323 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
324 >                if (o.equals(x)) {
325 >                    delete(i);
326 >                    return true;
327 >                }
328              }
335            i = (i + 1) & mask;
329          }
330          return false;
331      }
# Line 341 | Line 334 | public class ArrayDeque<E> extends Abstr
334       * Removes the last occurrence of the specified element in this
335       * deque (when traversing the deque from head to tail).
336       * If the deque does not contain the element, it is unchanged.
337 <     * More formally, removes the last element <tt>e</tt> such that
338 <     * <tt>o.equals(e)</tt> (if such an element exists).
339 <     * Returns <tt>true</tt> if this deque contained the specified element
337 >     * More formally, removes the last element {@code e} such that
338 >     * {@code o.equals(e)} (if such an element exists).
339 >     * Returns {@code true} if this deque contained the specified element
340       * (or equivalently, if this deque changed as a result of the call).
341       *
342       * @param o element to be removed from this deque, if present
343 <     * @return <tt>true</tt> if the deque contained the specified element
343 >     * @return {@code true} if the deque contained the specified element
344       */
345      public boolean removeLastOccurrence(Object o) {
346 <        if (o == null)
347 <            return false;
348 <        int mask = elements.length - 1;
349 <        int i = (tail - 1) & mask;
350 <        E x;
351 <        while ( (x = elements[i]) != null) {
352 <            if (o.equals(x)) {
353 <                delete(i);
361 <                return true;
346 >        if (o != null) {
347 >            int mask = elements.length - 1;
348 >            int i = (tail - 1) & mask;
349 >            for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
350 >                if (o.equals(x)) {
351 >                    delete(i);
352 >                    return true;
353 >                }
354              }
363            i = (i - 1) & mask;
355          }
356          return false;
357      }
# Line 373 | Line 364 | public class ArrayDeque<E> extends Abstr
364       * <p>This method is equivalent to {@link #addLast}.
365       *
366       * @param e the element to add
367 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
367 >     * @return {@code true} (as specified by {@link Collection#add})
368       * @throws NullPointerException if the specified element is null
369       */
370      public boolean add(E e) {
# Line 387 | Line 378 | public class ArrayDeque<E> extends Abstr
378       * <p>This method is equivalent to {@link #offerLast}.
379       *
380       * @param e the element to add
381 <     * @return <tt>true</tt> (as specified by {@link Queue#offer})
381 >     * @return {@code true} (as specified by {@link Queue#offer})
382       * @throws NullPointerException if the specified element is null
383       */
384      public boolean offer(E e) {
# Line 412 | Line 403 | public class ArrayDeque<E> extends Abstr
403      /**
404       * Retrieves and removes the head of the queue represented by this deque
405       * (in other words, the first element of this deque), or returns
406 <     * <tt>null</tt> if this deque is empty.
406 >     * {@code null} if this deque is empty.
407       *
408       * <p>This method is equivalent to {@link #pollFirst}.
409       *
410       * @return the head of the queue represented by this deque, or
411 <     *         <tt>null</tt> if this deque is empty
411 >     *         {@code null} if this deque is empty
412       */
413      public E poll() {
414          return pollFirst();
# Line 439 | Line 430 | public class ArrayDeque<E> extends Abstr
430  
431      /**
432       * Retrieves, but does not remove, the head of the queue represented by
433 <     * this deque, or returns <tt>null</tt> if this deque is empty.
433 >     * this deque, or returns {@code null} if this deque is empty.
434       *
435       * <p>This method is equivalent to {@link #peekFirst}.
436       *
437       * @return the head of the queue represented by this deque, or
438 <     *         <tt>null</tt> if this deque is empty
438 >     *         {@code null} if this deque is empty
439       */
440      public E peek() {
441          return peekFirst();
# Line 479 | Line 470 | public class ArrayDeque<E> extends Abstr
470          return removeFirst();
471      }
472  
473 +    private void checkInvariants() {
474 +        assert elements[tail] == null;
475 +        assert head == tail ? elements[head] == null :
476 +            (elements[head] != null &&
477 +             elements[(tail - 1) & (elements.length - 1)] != null);
478 +        assert elements[(head - 1) & (elements.length - 1)] == null;
479 +    }
480 +
481      /**
482       * Removes the element at the specified position in the elements array,
483       * adjusting head and tail as necessary.  This can result in motion of
# Line 490 | Line 489 | public class ArrayDeque<E> extends Abstr
489       * @return true if elements moved backwards
490       */
491      private boolean delete(int i) {
492 <        int mask = elements.length - 1;
493 <        int front = (i - head) & mask;
494 <        int back  = (tail - i) & mask;
495 <
496 <        // Invariant: head <= i < tail mod circularity
497 <        if (front >= ((tail - head) & mask))
498 <            throw new ConcurrentModificationException();
499 <
500 <        // Optimize for least element motion
501 <        if (front < back) {
502 <            if (head <= i) {
503 <                System.arraycopy(elements, head, elements, head + 1, front);
504 <            } else { // Wrap around
505 <                elements[0] = elements[mask];
506 <                System.arraycopy(elements, 0, elements, 1, i);
507 <                System.arraycopy(elements, head, elements, head + 1, mask - head);
508 <            }
509 <            elements[head] = null;
510 <            head = (head + 1) & mask;
492 >        checkInvariants();
493 >        final Object[] elements = this.elements;
494 >        final int mask = elements.length - 1;
495 >        final int h = head;
496 >        final int t = tail;
497 >        final int front = (i - h) & mask;
498 >        final int back  = (t - i) & mask;
499 >
500 >        // Invariant: head <= i < tail mod circularity
501 >        if (front >= ((t - h) & mask))
502 >            throw new ConcurrentModificationException();
503 >
504 >        // Optimize for least element motion
505 >        if (front < back) {
506 >            if (h <= i) {
507 >                System.arraycopy(elements, h, elements, h + 1, front);
508 >            } else { // Wrap around
509 >                System.arraycopy(elements, 0, elements, 1, i);
510 >                elements[0] = elements[mask];
511 >                System.arraycopy(elements, h, elements, h + 1, mask - h);
512 >            }
513 >            elements[h] = null;
514 >            head = (h + 1) & mask;
515              return false;
516 <        } else {
517 <            int t = tail;
518 <            tail = (tail - 1) & mask;
519 <            if (i < t) { // Copy the null tail as well
520 <                System.arraycopy(elements, i + 1, elements, i, back);
521 <            } else {     // Wrap around
522 <                elements[mask] = elements[0];
523 <                System.arraycopy(elements, i + 1, elements, i, mask - i);
524 <                System.arraycopy(elements, 1, elements, 0, t);
525 <            }
516 >        } else {
517 >            if (i < t) { // Copy the null tail as well
518 >                System.arraycopy(elements, i + 1, elements, i, back);
519 >                tail = t - 1;
520 >            } else { // Wrap around
521 >                System.arraycopy(elements, i + 1, elements, i, mask - i);
522 >                elements[mask] = elements[0];
523 >                System.arraycopy(elements, 1, elements, 0, t);
524 >                tail = (t - 1) & mask;
525 >            }
526              return true;
527 <        }
527 >        }
528      }
529  
530      // *** Collection Methods ***
# Line 536 | Line 539 | public class ArrayDeque<E> extends Abstr
539      }
540  
541      /**
542 <     * Returns <tt>true</tt> if this deque contains no elements.
542 >     * Returns {@code true} if this deque contains no elements.
543       *
544 <     * @return <tt>true</tt> if this deque contains no elements
544 >     * @return {@code true} if this deque contains no elements
545       */
546      public boolean isEmpty() {
547          return head == tail;
# Line 583 | Line 586 | public class ArrayDeque<E> extends Abstr
586          }
587  
588          public E next() {
586            E result;
589              if (cursor == fence)
590                  throw new NoSuchElementException();
591 +            @SuppressWarnings("unchecked")
592 +            E result = (E) elements[cursor];
593              // This check doesn't catch all possible comodifications,
594              // but does catch the ones that corrupt traversal
595 <            if (tail != fence || (result = elements[cursor]) == null)
595 >            if (tail != fence || result == null)
596                  throw new ConcurrentModificationException();
597              lastRet = cursor;
598              cursor = (cursor + 1) & (elements.length - 1);
# Line 598 | Line 602 | public class ArrayDeque<E> extends Abstr
602          public void remove() {
603              if (lastRet < 0)
604                  throw new IllegalStateException();
605 <            if (delete(lastRet)) // if left-shifted, undo increment in next()
605 >            if (delete(lastRet)) { // if left-shifted, undo increment in next()
606                  cursor = (cursor - 1) & (elements.length - 1);
607 +                fence = tail;
608 +            }
609              lastRet = -1;
604            fence = tail;
610          }
611      }
612  
613 <
613 >    /**
614 >     * This class is nearly a mirror-image of DeqIterator, using tail
615 >     * instead of head for initial cursor, and head instead of tail
616 >     * for fence.
617 >     */
618      private class DescendingIterator implements Iterator<E> {
619 <        /*
620 <         * This class is nearly a mirror-image of DeqIterator, using
621 <         * (tail-1) instead of head for initial cursor, (head-1)
613 <         * instead of tail for fence, and elements.length instead of -1
614 <         * for sentinel. It shares the same structure, but not many
615 <         * actual lines of code.
616 <         */
617 <        private int cursor = (tail - 1) & (elements.length - 1);
618 <        private int fence =  (head - 1) & (elements.length - 1);
619 <        private int lastRet = elements.length;
619 >        private int cursor = tail;
620 >        private int fence = head;
621 >        private int lastRet = -1;
622  
623          public boolean hasNext() {
624              return cursor != fence;
625          }
626  
627          public E next() {
626            E result;
628              if (cursor == fence)
629                  throw new NoSuchElementException();
630 <            if (((head - 1) & (elements.length - 1)) != fence ||
631 <                (result = elements[cursor]) == null)
630 >            cursor = (cursor - 1) & (elements.length - 1);
631 >            @SuppressWarnings("unchecked")
632 >            E result = (E) elements[cursor];
633 >            if (head != fence || result == null)
634                  throw new ConcurrentModificationException();
635              lastRet = cursor;
633            cursor = (cursor - 1) & (elements.length - 1);
636              return result;
637          }
638  
639          public void remove() {
640 <            if (lastRet >= elements.length)
640 >            if (lastRet < 0)
641                  throw new IllegalStateException();
642 <            if (!delete(lastRet))
642 >            if (!delete(lastRet)) {
643                  cursor = (cursor + 1) & (elements.length - 1);
644 <            lastRet = elements.length;
645 <            fence = (head - 1) & (elements.length - 1);
644 >                fence = head;
645 >            }
646 >            lastRet = -1;
647          }
648      }
649  
650      /**
651 <     * Returns <tt>true</tt> if this deque contains the specified element.
652 <     * More formally, returns <tt>true</tt> if and only if this deque contains
653 <     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
651 >     * Returns {@code true} if this deque contains the specified element.
652 >     * More formally, returns {@code true} if and only if this deque contains
653 >     * at least one element {@code e} such that {@code o.equals(e)}.
654       *
655       * @param o object to be checked for containment in this deque
656 <     * @return <tt>true</tt> if this deque contains the specified element
656 >     * @return {@code true} if this deque contains the specified element
657       */
658      public boolean contains(Object o) {
659 <        if (o == null)
660 <            return false;
661 <        int mask = elements.length - 1;
662 <        int i = head;
663 <        E x;
664 <        while ( (x = elements[i]) != null) {
665 <            if (o.equals(x))
663 <                return true;
664 <            i = (i + 1) & mask;
659 >        if (o != null) {
660 >            int mask = elements.length - 1;
661 >            int i = head;
662 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
663 >                if (o.equals(x))
664 >                    return true;
665 >            }
666          }
667          return false;
668      }
# Line 669 | Line 670 | public class ArrayDeque<E> extends Abstr
670      /**
671       * Removes a single instance of the specified element from this deque.
672       * If the deque does not contain the element, it is unchanged.
673 <     * More formally, removes the first element <tt>e</tt> such that
674 <     * <tt>o.equals(e)</tt> (if such an element exists).
675 <     * Returns <tt>true</tt> if this deque contained the specified element
673 >     * More formally, removes the first element {@code e} such that
674 >     * {@code o.equals(e)} (if such an element exists).
675 >     * Returns {@code true} if this deque contained the specified element
676       * (or equivalently, if this deque changed as a result of the call).
677       *
678 <     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
678 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
679       *
680       * @param o element to be removed from this deque, if present
681 <     * @return <tt>true</tt> if this deque contained the specified element
681 >     * @return {@code true} if this deque contained the specified element
682       */
683      public boolean remove(Object o) {
684          return removeFirstOccurrence(o);
# Line 715 | Line 716 | public class ArrayDeque<E> extends Abstr
716       * @return an array containing all of the elements in this deque
717       */
718      public Object[] toArray() {
719 <        return copyElements(new Object[size()]);
719 >        final int head = this.head;
720 >        final int tail = this.tail;
721 >        boolean wrap = (tail < head);
722 >        int end = wrap ? tail + elements.length : tail;
723 >        Object[] a = Arrays.copyOfRange(elements, head, end);
724 >        if (wrap)
725 >            System.arraycopy(elements, 0, a, elements.length - head, tail);
726 >        return a;
727      }
728  
729      /**
# Line 729 | Line 737 | public class ArrayDeque<E> extends Abstr
737       * <p>If this deque fits in the specified array with room to spare
738       * (i.e., the array has more elements than this deque), the element in
739       * the array immediately following the end of the deque is set to
740 <     * <tt>null</tt>.
740 >     * {@code null}.
741       *
742       * <p>Like the {@link #toArray()} method, this method acts as bridge between
743       * array-based and collection-based APIs.  Further, this method allows
744       * precise control over the runtime type of the output array, and may,
745       * under certain circumstances, be used to save allocation costs.
746       *
747 <     * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
747 >     * <p>Suppose {@code x} is a deque known to contain only strings.
748       * The following code can be used to dump the deque into a newly
749 <     * allocated array of <tt>String</tt>:
749 >     * allocated array of {@code String}:
750       *
751 <     * <pre>
744 <     *     String[] y = x.toArray(new String[0]);</pre>
751 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
752       *
753 <     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
754 <     * <tt>toArray()</tt>.
753 >     * Note that {@code toArray(new Object[0])} is identical in function to
754 >     * {@code toArray()}.
755       *
756       * @param a the array into which the elements of the deque are to
757       *          be stored, if it is big enough; otherwise, a new array of the
# Line 755 | Line 762 | public class ArrayDeque<E> extends Abstr
762       *         this deque
763       * @throws NullPointerException if the specified array is null
764       */
765 +    @SuppressWarnings("unchecked")
766      public <T> T[] toArray(T[] a) {
767 <        int size = size();
768 <        if (a.length < size)
769 <            a = (T[])java.lang.reflect.Array.newInstance(
770 <                    a.getClass().getComponentType(), size);
771 <        copyElements(a);
772 <        if (a.length > size)
773 <            a[size] = null;
767 >        final int head = this.head;
768 >        final int tail = this.tail;
769 >        boolean wrap = (tail < head);
770 >        int size = (tail - head) + (wrap ? elements.length : 0);
771 >        int firstLeg = size - (wrap ? tail : 0);
772 >        int len = a.length;
773 >        if (size > len) {
774 >            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
775 >                                         a.getClass());
776 >        } else {
777 >            System.arraycopy(elements, head, a, 0, firstLeg);
778 >            if (size < len)
779 >                a[size] = null;
780 >        }
781 >        if (wrap)
782 >            System.arraycopy(elements, 0, a, firstLeg, tail);
783          return a;
784      }
785  
# Line 775 | Line 792 | public class ArrayDeque<E> extends Abstr
792       */
793      public ArrayDeque<E> clone() {
794          try {
795 +            @SuppressWarnings("unchecked")
796              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
797 <            // 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);
797 >            result.elements = Arrays.copyOf(elements, elements.length);
798              return result;
783
799          } catch (CloneNotSupportedException e) {
800              throw new AssertionError();
801          }
802      }
803  
789    /**
790     * Appease the serialization gods.
791     */
804      private static final long serialVersionUID = 2340985798034038923L;
805  
806      /**
807 <     * Serialize this deque.
807 >     * Saves this deque to a stream (that is, serializes it).
808       *
809 <     * @serialData The current size (<tt>int</tt>) of the deque,
809 >     * @param s the stream
810 >     * @throws java.io.IOException if an I/O error occurs
811 >     * @serialData The current size ({@code int}) of the deque,
812       * followed by all of its elements (each an object reference) in
813       * first-to-last order.
814       */
815 <    private void writeObject(ObjectOutputStream s) throws IOException {
815 >    private void writeObject(java.io.ObjectOutputStream s)
816 >            throws java.io.IOException {
817          s.defaultWriteObject();
818  
819          // Write out size
# Line 811 | Line 826 | public class ArrayDeque<E> extends Abstr
826      }
827  
828      /**
829 <     * Deserialize this deque.
829 >     * Reconstitutes this deque from a stream (that is, deserializes it).
830 >     * @param s the stream
831 >     * @throws ClassNotFoundException if the class of a serialized object
832 >     *         could not be found
833 >     * @throws java.io.IOException if an I/O error occurs
834       */
835 <    private void readObject(ObjectInputStream s)
836 <            throws IOException, ClassNotFoundException {
835 >    private void readObject(java.io.ObjectInputStream s)
836 >            throws java.io.IOException, ClassNotFoundException {
837          s.defaultReadObject();
838  
839          // Read in size and allocate array
# Line 825 | Line 844 | public class ArrayDeque<E> extends Abstr
844  
845          // Read in all elements in the proper order.
846          for (int i = 0; i < size; i++)
847 <            elements[i] = (E)s.readObject();
847 >            elements[i] = s.readObject();
848 >    }
849 >
850 >    public Spliterator<E> spliterator() {
851 >        return new DeqSpliterator<E>(this, -1, -1);
852 >    }
853 >
854 >    static final class DeqSpliterator<E> implements Spliterator<E> {
855 >        private final ArrayDeque<E> deq;
856 >        private int fence;  // -1 until first use
857 >        private int index;  // current index, modified on traverse/split
858 >
859 >        /** Creates new spliterator covering the given array and range */
860 >        DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
861 >            this.deq = deq;
862 >            this.index = origin;
863 >            this.fence = fence;
864 >        }
865 >
866 >        private int getFence() { // force initialization
867 >            int t;
868 >            if ((t = fence) < 0) {
869 >                t = fence = deq.tail;
870 >                index = deq.head;
871 >            }
872 >            return t;
873 >        }
874 >
875 >        public Spliterator<E> trySplit() {
876 >            int t = getFence(), h = index, n = deq.elements.length;
877 >            if (h != t && ((h + 1) & (n - 1)) != t) {
878 >                if (h > t)
879 >                    t += n;
880 >                int m = ((h + t) >>> 1) & (n - 1);
881 >                return new DeqSpliterator<>(deq, h, index = m);
882 >            }
883 >            return null;
884 >        }
885 >
886 >        public void forEachRemaining(Consumer<? super E> consumer) {
887 >            if (consumer == null)
888 >                throw new NullPointerException();
889 >            Object[] a = deq.elements;
890 >            int m = a.length - 1, f = getFence(), i = index;
891 >            index = f;
892 >            while (i != f) {
893 >                @SuppressWarnings("unchecked") E e = (E)a[i];
894 >                i = (i + 1) & m;
895 >                if (e == null)
896 >                    throw new ConcurrentModificationException();
897 >                consumer.accept(e);
898 >            }
899 >        }
900 >
901 >        public boolean tryAdvance(Consumer<? super E> consumer) {
902 >            if (consumer == null)
903 >                throw new NullPointerException();
904 >            Object[] a = deq.elements;
905 >            int m = a.length - 1, f = getFence(), i = index;
906 >            if (i != f) {
907 >                @SuppressWarnings("unchecked") E e = (E)a[i];
908 >                index = (i + 1) & m;
909 >                if (e == null)
910 >                    throw new ConcurrentModificationException();
911 >                consumer.accept(e);
912 >                return true;
913 >            }
914 >            return false;
915 >        }
916 >
917 >        public long estimateSize() {
918 >            int n = getFence() - index;
919 >            if (n < 0)
920 >                n += deq.elements.length;
921 >            return (long) n;
922 >        }
923  
924 +        @Override
925 +        public int characteristics() {
926 +            return Spliterator.ORDERED | Spliterator.SIZED |
927 +                Spliterator.NONNULL | Spliterator.SUBSIZED;
928 +        }
929      }
930 +
931   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines