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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines