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.39 by jsr166, Tue Feb 21 01:54:03 2012 UTC vs.
Revision 1.51 by jsr166, Wed Feb 20 12:39:06 2013 UTC

# Line 4 | Line 4
4   */
5  
6   package java.util;
7 + import java.io.Serializable;
8 + import java.util.function.Consumer;
9 + import java.util.stream.Stream;
10 + import java.util.stream.Streams;
11  
12   /**
13   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 14 | Line 18 | package java.util;
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 33 | Line 39 | package java.util;
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 51 | Line 57 | package java.util;
57   * @param <E> the type of elements held in this collection
58   */
59   public class ArrayDeque<E> extends AbstractCollection<E>
60 <                           implements Deque<E>, Cloneable, java.io.Serializable
60 >                           implements Deque<E>, Cloneable, Serializable
61   {
62      /**
63       * The array in which the elements of the deque are stored.
# Line 63 | 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 Object[] 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 131 | Line 137 | public class ArrayDeque<E> extends Abstr
137      }
138  
139      /**
134     * Copies the elements from our element array into the specified array,
135     * in order (from first to last element in the deque).  It is assumed
136     * that the array is large enough to hold all elements in the deque.
137     *
138     * @return its argument
139     */
140    private <T> T[] copyElements(T[] a) {
141        if (head < tail) {
142            System.arraycopy(elements, head, a, 0, size());
143        } else if (head > tail) {
144            int headPortionLen = elements.length - head;
145            System.arraycopy(elements, head, a, 0, headPortionLen);
146            System.arraycopy(elements, 0, a, headPortionLen, tail);
147        }
148        return a;
149    }
150
151    /**
140       * Constructs an empty array deque with an initial capacity
141       * sufficient to hold 16 elements.
142       */
# Line 219 | 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 231 | 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 319 | Line 307 | public class ArrayDeque<E> extends Abstr
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)
# Line 347 | Line 335 | public class ArrayDeque<E> extends Abstr
335       * Removes the last occurrence of the specified element in this
336       * deque (when traversing the deque from head to tail).
337       * If the deque does not contain the element, it is unchanged.
338 <     * More formally, removes the last element <tt>e</tt> such that
339 <     * <tt>o.equals(e)</tt> (if such an element exists).
340 <     * Returns <tt>true</tt> if this deque contained the specified element
338 >     * More formally, removes the last element {@code e} such that
339 >     * {@code o.equals(e)} (if such an element exists).
340 >     * Returns {@code true} if this deque contained the specified element
341       * (or equivalently, if this deque changed as a result of the call).
342       *
343       * @param o element to be removed from this deque, if present
344 <     * @return <tt>true</tt> if the deque contained the specified element
344 >     * @return {@code true} if the deque contained the specified element
345       */
346      public boolean removeLastOccurrence(Object o) {
347          if (o == null)
# Line 379 | Line 367 | public class ArrayDeque<E> extends Abstr
367       * <p>This method is equivalent to {@link #addLast}.
368       *
369       * @param e the element to add
370 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
370 >     * @return {@code true} (as specified by {@link Collection#add})
371       * @throws NullPointerException if the specified element is null
372       */
373      public boolean add(E e) {
# Line 393 | Line 381 | public class ArrayDeque<E> extends Abstr
381       * <p>This method is equivalent to {@link #offerLast}.
382       *
383       * @param e the element to add
384 <     * @return <tt>true</tt> (as specified by {@link Queue#offer})
384 >     * @return {@code true} (as specified by {@link Queue#offer})
385       * @throws NullPointerException if the specified element is null
386       */
387      public boolean offer(E e) {
# Line 418 | Line 406 | public class ArrayDeque<E> extends Abstr
406      /**
407       * Retrieves and removes the head of the queue represented by this deque
408       * (in other words, the first element of this deque), or returns
409 <     * <tt>null</tt> if this deque is empty.
409 >     * {@code null} if this deque is empty.
410       *
411       * <p>This method is equivalent to {@link #pollFirst}.
412       *
413       * @return the head of the queue represented by this deque, or
414 <     *         <tt>null</tt> if this deque is empty
414 >     *         {@code null} if this deque is empty
415       */
416      public E poll() {
417          return pollFirst();
# Line 445 | Line 433 | public class ArrayDeque<E> extends Abstr
433  
434      /**
435       * Retrieves, but does not remove, the head of the queue represented by
436 <     * this deque, or returns <tt>null</tt> if this deque is empty.
436 >     * this deque, or returns {@code null} if this deque is empty.
437       *
438       * <p>This method is equivalent to {@link #peekFirst}.
439       *
440       * @return the head of the queue represented by this deque, or
441 <     *         <tt>null</tt> if this deque is empty
441 >     *         {@code null} if this deque is empty
442       */
443      public E peek() {
444          return peekFirst();
# Line 554 | Line 542 | public class ArrayDeque<E> extends Abstr
542      }
543  
544      /**
545 <     * Returns <tt>true</tt> if this deque contains no elements.
545 >     * Returns {@code true} if this deque contains no elements.
546       *
547 <     * @return <tt>true</tt> if this deque contains no elements
547 >     * @return {@code true} if this deque contains no elements
548       */
549      public boolean isEmpty() {
550          return head == tail;
# Line 663 | Line 651 | public class ArrayDeque<E> extends Abstr
651      }
652  
653      /**
654 <     * Returns <tt>true</tt> if this deque contains the specified element.
655 <     * More formally, returns <tt>true</tt> if and only if this deque contains
656 <     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
654 >     * Returns {@code true} if this deque contains the specified element.
655 >     * More formally, returns {@code true} if and only if this deque contains
656 >     * at least one element {@code e} such that {@code o.equals(e)}.
657       *
658       * @param o object to be checked for containment in this deque
659 <     * @return <tt>true</tt> if this deque contains the specified element
659 >     * @return {@code true} if this deque contains the specified element
660       */
661      public boolean contains(Object o) {
662          if (o == null)
# Line 687 | Line 675 | public class ArrayDeque<E> extends Abstr
675      /**
676       * Removes a single instance of the specified element from this deque.
677       * If the deque does not contain the element, it is unchanged.
678 <     * More formally, removes the first element <tt>e</tt> such that
679 <     * <tt>o.equals(e)</tt> (if such an element exists).
680 <     * Returns <tt>true</tt> if this deque contained the specified element
678 >     * More formally, removes the first element {@code e} such that
679 >     * {@code o.equals(e)} (if such an element exists).
680 >     * Returns {@code true} if this deque contained the specified element
681       * (or equivalently, if this deque changed as a result of the call).
682       *
683 <     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
683 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
684       *
685       * @param o element to be removed from this deque, if present
686 <     * @return <tt>true</tt> if this deque contained the specified element
686 >     * @return {@code true} if this deque contained the specified element
687       */
688      public boolean remove(Object o) {
689          return removeFirstOccurrence(o);
# Line 733 | Line 721 | public class ArrayDeque<E> extends Abstr
721       * @return an array containing all of the elements in this deque
722       */
723      public Object[] toArray() {
724 <        return copyElements(new Object[size()]);
724 >        final int head = this.head;
725 >        final int tail = this.tail;
726 >        boolean wrap = (tail < head);
727 >        int end = wrap ? tail + elements.length : tail;
728 >        Object[] a = Arrays.copyOfRange(elements, head, end);
729 >        if (wrap)
730 >            System.arraycopy(elements, 0, a, elements.length - head, tail);
731 >        return a;
732      }
733  
734      /**
# Line 747 | Line 742 | public class ArrayDeque<E> extends Abstr
742       * <p>If this deque fits in the specified array with room to spare
743       * (i.e., the array has more elements than this deque), the element in
744       * the array immediately following the end of the deque is set to
745 <     * <tt>null</tt>.
745 >     * {@code null}.
746       *
747       * <p>Like the {@link #toArray()} method, this method acts as bridge between
748       * array-based and collection-based APIs.  Further, this method allows
749       * precise control over the runtime type of the output array, and may,
750       * under certain circumstances, be used to save allocation costs.
751       *
752 <     * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
752 >     * <p>Suppose {@code x} is a deque known to contain only strings.
753       * The following code can be used to dump the deque into a newly
754 <     * allocated array of <tt>String</tt>:
754 >     * allocated array of {@code String}:
755       *
756       *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
757       *
758 <     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
759 <     * <tt>toArray()</tt>.
758 >     * Note that {@code toArray(new Object[0])} is identical in function to
759 >     * {@code toArray()}.
760       *
761       * @param a the array into which the elements of the deque are to
762       *          be stored, if it is big enough; otherwise, a new array of the
# Line 774 | Line 769 | public class ArrayDeque<E> extends Abstr
769       */
770      @SuppressWarnings("unchecked")
771      public <T> T[] toArray(T[] a) {
772 <        int size = size();
773 <        if (a.length < size)
774 <            a = (T[])java.lang.reflect.Array.newInstance(
775 <                    a.getClass().getComponentType(), size);
776 <        copyElements(a);
777 <        if (a.length > size)
778 <            a[size] = null;
772 >        final int head = this.head;
773 >        final int tail = this.tail;
774 >        boolean wrap = (tail < head);
775 >        int size = (tail - head) + (wrap ? elements.length : 0);
776 >        int firstLeg = size - (wrap ? tail : 0);
777 >        int len = a.length;
778 >        if (size > len) {
779 >            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
780 >                                         a.getClass());
781 >        } else {
782 >            System.arraycopy(elements, head, a, 0, firstLeg);
783 >            if (size < len)
784 >                a[size] = null;
785 >        }
786 >        if (wrap)
787 >            System.arraycopy(elements, 0, a, firstLeg, tail);
788          return a;
789      }
790  
# Line 807 | Line 811 | public class ArrayDeque<E> extends Abstr
811      /**
812       * Saves this deque to a stream (that is, serializes it).
813       *
814 <     * @serialData The current size (<tt>int</tt>) of the deque,
814 >     * @serialData The current size ({@code int}) of the deque,
815       * followed by all of its elements (each an object reference) in
816       * first-to-last order.
817       */
# Line 841 | Line 845 | public class ArrayDeque<E> extends Abstr
845          for (int i = 0; i < size; i++)
846              elements[i] = s.readObject();
847      }
848 +
849 +    Spliterator<E> spliterator() {
850 +        return new DeqSpliterator<E>(this, -1, -1);
851 +    }
852 +
853 +    public Stream<E> stream() {
854 +        return Streams.stream(spliterator());
855 +    }
856 +
857 +    public Stream<E> parallelStream() {
858 +        return Streams.parallelStream(spliterator());
859 +    }
860 +
861 +    static final class DeqSpliterator<E> implements Spliterator<E> {
862 +        private final ArrayDeque<E> deq;
863 +        private int fence;  // -1 until first use
864 +        private int index;  // current index, modified on traverse/split
865 +
866 +        /** Creates new spliterator covering the given array and range */
867 +        DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
868 +            this.deq = deq;
869 +            this.index = origin;
870 +            this.fence = fence;
871 +        }
872 +
873 +        private int getFence() { // force initialization
874 +            int t;
875 +            if ((t = fence) < 0) {
876 +                t = fence = deq.tail;
877 +                index = deq.head;
878 +            }
879 +            return t;
880 +        }
881 +
882 +        public DeqSpliterator<E> trySplit() {
883 +            int t = getFence(), h = index, n = deq.elements.length;
884 +            if (h != t && ((h + 1) & (n - 1)) != t) {
885 +                if (h > t)
886 +                    t += n;
887 +                int m = ((h + t) >>> 1) & (n - 1);
888 +                return new DeqSpliterator<>(deq, h, index = m);
889 +            }
890 +            return null;
891 +        }
892 +
893 +        public void forEach(Consumer<? super E> consumer) {
894 +            if (consumer == null)
895 +                throw new NullPointerException();
896 +            Object[] a = deq.elements;
897 +            int m = a.length - 1, f = getFence(), i = index;
898 +            index = f;
899 +            while (i != f) {
900 +                @SuppressWarnings("unchecked") E e = (E)a[i];
901 +                i = (i + 1) & m;
902 +                if (e == null)
903 +                    throw new ConcurrentModificationException();
904 +                consumer.accept(e);
905 +            }
906 +        }
907 +
908 +        public boolean tryAdvance(Consumer<? super E> consumer) {
909 +            if (consumer == null)
910 +                throw new NullPointerException();
911 +            Object[] a = deq.elements;
912 +            int m = a.length - 1, f = getFence(), i = index;
913 +            if (i != fence) {
914 +                @SuppressWarnings("unchecked") E e = (E)a[i];
915 +                index = (i + 1) & m;
916 +                if (e == null)
917 +                    throw new ConcurrentModificationException();
918 +                consumer.accept(e);
919 +                return true;
920 +            }
921 +            return false;
922 +        }
923 +
924 +        public long estimateSize() {
925 +            int n = getFence() - index;
926 +            if (n < 0)
927 +                n += deq.elements.length;
928 +            return (long) n;
929 +        }
930 +
931 +        @Override
932 +        public int characteristics() {
933 +            return Spliterator.ORDERED | Spliterator.SIZED |
934 +                Spliterator.NONNULL | Spliterator.SUBSIZED;
935 +        }
936 +    }
937 +
938   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines