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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines