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.43 by jsr166, Wed Jan 16 21:25:33 2013 UTC vs.
Revision 1.53 by dl, Wed Mar 13 12:38:56 2013 UTC

# Line 1 | Line 1
1   /*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation.  Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 */
24
25 /*
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
29 * file:
30 *
2   * Written by Josh Bloch of Google Inc. and released to the public domain,
3   * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
4   */
5  
6   package java.util;
7 < import java.util.Spliterator;
7 > import java.io.Serializable;
8 > import java.util.function.Consumer;
9   import java.util.stream.Stream;
10   import java.util.stream.Streams;
39 import java.util.function.Block;
11  
12   /**
13   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 48 | Line 19 | import java.util.function.Block;
19   * when used as a queue.
20   *
21   * <p>Most {@code ArrayDeque} 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.
27 < *
28 < * <p>The iterators returned by this class's {@code iterator} method are
29 < * <i>fail-fast</i>: If the deque is modified at any time after the iterator
30 < * is created, in any way except through the iterator's own {@code remove}
31 < * method, the iterator will generally throw a {@link
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 {@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 84 | Line 57 | import java.util.function.Block;
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 164 | Line 137 | public class ArrayDeque<E> extends Abstr
137      }
138  
139      /**
167     * Copies the elements from our element array into the specified array,
168     * in order (from first to last element in the deque).  It is assumed
169     * that the array is large enough to hold all elements in the deque.
170     *
171     * @return its argument
172     */
173    private <T> T[] copyElements(T[] a) {
174        if (head < tail) {
175            System.arraycopy(elements, head, a, 0, size());
176        } else if (head > tail) {
177            int headPortionLen = elements.length - head;
178            System.arraycopy(elements, head, a, 0, headPortionLen);
179            System.arraycopy(elements, 0, a, headPortionLen, tail);
180        }
181        return a;
182    }
183
184    /**
140       * Constructs an empty array deque with an initial capacity
141       * sufficient to hold 16 elements.
142       */
# Line 658 | Line 613 | public class ArrayDeque<E> extends Abstr
613          }
614      }
615  
616 +    /**
617 +     * This class is nearly a mirror-image of DeqIterator, using tail
618 +     * instead of head for initial cursor, and head instead of tail
619 +     * for fence.
620 +     */
621      private class DescendingIterator implements Iterator<E> {
662        /*
663         * This class is nearly a mirror-image of DeqIterator, using
664         * tail instead of head for initial cursor, and head instead of
665         * tail for fence.
666         */
622          private int cursor = tail;
623          private int fence = head;
624          private int lastRet = -1;
# Line 725 | Line 680 | public class ArrayDeque<E> extends Abstr
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 {@code true} if this deque contained the specified element
# Line 766 | 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 807 | 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 875 | Line 846 | public class ArrayDeque<E> extends Abstr
846              elements[i] = s.readObject();
847      }
848  
849 <    public Stream<E> stream() {
850 <        int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_SIZED;
880 <        return Streams.stream
881 <            (() -> new DeqSpliterator<E>(this, head, tail), flags);
882 <    }
883 <    public Stream<E> parallelStream() {
884 <        int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_SIZED;
885 <        return Streams.parallelStream
886 <            (() -> new DeqSpliterator<E>(this, head, tail), flags);
849 >    public Spliterator<E> spliterator() {
850 >        return new DeqSpliterator<E>(this, -1, -1);
851      }
852  
853 <
890 <    static final class DeqSpliterator<E> implements Spliterator<E>, Iterator<E> {
853 >    static final class DeqSpliterator<E> implements Spliterator<E> {
854          private final ArrayDeque<E> deq;
855 <        private final Object[] array;
856 <        private final int fence;  // initially tail
894 <        private int index;        // current index, modified on traverse/split
855 >        private int fence;  // -1 until first use
856 >        private int index;  // current index, modified on traverse/split
857  
858 <        /** Create new spliterator covering the given array and range */
858 >        /** Creates new spliterator covering the given array and range */
859          DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
860 <            this.deq = deq; this.array = deq.elements;
861 <            this.index = origin; this.fence = fence;
860 >            this.deq = deq;
861 >            this.index = origin;
862 >            this.fence = fence;
863          }
864  
865 <        public DeqSpliterator<E> trySplit() {
866 <            int n = array.length;
867 <            int h = index, t = fence;
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<E>(deq, h, index = m);
880 >                return new DeqSpliterator<>(deq, h, index = m);
881              }
882              return null;
883          }
884  
885 <        @SuppressWarnings("unchecked")
886 <        public void forEach(Block<? super E> block) {
916 <            if (block == null)
885 >        public void forEach(Consumer<? super E> consumer) {
886 >            if (consumer == null)
887                  throw new NullPointerException();
888 <            Object[] a = array;
889 <            if (a != deq.elements)
920 <                throw new ConcurrentModificationException();
921 <            int m = a.length - 1, f = fence, i = index;
888 >            Object[] a = deq.elements;
889 >            int m = a.length - 1, f = getFence(), i = index;
890              index = f;
891              while (i != f) {
892 <                Object e = a[i];
892 >                @SuppressWarnings("unchecked") E e = (E)a[i];
893 >                i = (i + 1) & m;
894                  if (e == null)
895                      throw new ConcurrentModificationException();
896 <                block.accept((E)e);
928 <                i = (i + 1) & m;
896 >                consumer.accept(e);
897              }
898          }
899  
900 <        @SuppressWarnings("unchecked")
901 <        public boolean tryAdvance(Block<? super E> block) {
934 <            if (block == null)
900 >        public boolean tryAdvance(Consumer<? super E> consumer) {
901 >            if (consumer == null)
902                  throw new NullPointerException();
903 <            Object[] a = array;
904 <            if (a != deq.elements)
938 <                throw new ConcurrentModificationException();
939 <            int m = a.length - 1, i = index;
903 >            Object[] a = deq.elements;
904 >            int m = a.length - 1, f = getFence(), i = index;
905              if (i != fence) {
906 <                Object e = a[i];
906 >                @SuppressWarnings("unchecked") E e = (E)a[i];
907 >                index = (i + 1) & m;
908                  if (e == null)
909                      throw new ConcurrentModificationException();
910 <                block.accept((E)e);
945 <                index = (i + 1) & m;
910 >                consumer.accept(e);
911                  return true;
912              }
913              return false;
914          }
915  
951        // Iterator support
952        public Iterator<E> iterator() {
953            return this;
954        }
955
956        public boolean hasNext() {
957            return index >= 0 && index != fence;
958        }
959
960        @SuppressWarnings("unchecked")
961            public E next() {
962            if (index < 0 || index == fence)
963                throw new NoSuchElementException();
964            Object[] a = array;
965            if (a != deq.elements)
966                throw new ConcurrentModificationException();
967            Object e = a[index];
968            if (e == null)
969                throw new ConcurrentModificationException();
970            index = (index + 1) & (a.length - 1);
971            return (E) e;
972        }
973
974        public void remove() { throw new UnsupportedOperationException(); }
975
976        // Other spliterator methods
916          public long estimateSize() {
917 <            int n = fence - index;
917 >            int n = getFence() - index;
918              if (n < 0)
919 <                n += array.length;
920 <            return (long)n;
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          }
983        public boolean hasExactSize() { return true; }
984        public boolean hasExactSplits() { return true; }
928      }
929  
930   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines