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.73 by jsr166, Sun Oct 11 00:50:06 2015 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;
8 < import java.util.stream.Stream;
9 < import java.util.stream.Streams;
39 < import java.util.function.Block;
7 >
8 > import java.io.Serializable;
9 > import java.util.function.Consumer;
10  
11   /**
12   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 48 | Line 18 | import java.util.function.Block;
18   * when used as a queue.
19   *
20   * <p>Most {@code ArrayDeque} 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.
26 < *
27 < * <p>The iterators returned by this class's {@code iterator} method are
28 < * <i>fail-fast</i>: If the deque is modified at any time after the iterator
29 < * is created, in any way except through the iterator's own {@code remove}
30 < * method, the iterator will generally throw a {@link
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 {@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 81 | Line 53 | import java.util.function.Block;
53   *
54   * @author  Josh Bloch and Doug Lea
55   * @since   1.6
56 < * @param <E> the type of elements held in this collection
56 > * @param <E> the type of elements held in this deque
57   */
58   public class ArrayDeque<E> extends AbstractCollection<E>
59 <                           implements Deque<E>, Cloneable, java.io.Serializable
59 >                           implements Deque<E>, Cloneable, Serializable
60   {
61      /**
62       * The array in which the elements of the deque are stored.
# Line 137 | Line 109 | public class ArrayDeque<E> extends Abstr
109              initialCapacity |= (initialCapacity >>> 16);
110              initialCapacity++;
111  
112 <            if (initialCapacity < 0)   // Too many elements, must back off
113 <                initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
112 >            if (initialCapacity < 0)    // Too many elements, must back off
113 >                initialCapacity >>>= 1; // Good luck allocating 2^30 elements
114          }
115          elements = new Object[initialCapacity];
116      }
# Line 164 | Line 136 | public class ArrayDeque<E> extends Abstr
136      }
137  
138      /**
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    /**
139       * Constructs an empty array deque with an initial capacity
140       * sufficient to hold 16 elements.
141       */
# Line 293 | Line 247 | public class ArrayDeque<E> extends Abstr
247      }
248  
249      public E pollFirst() {
250 <        int h = head;
250 >        final Object[] elements = this.elements;
251 >        final int h = head;
252          @SuppressWarnings("unchecked")
253          E result = (E) elements[h];
254          // Element is null if deque empty
255 <        if (result == null)
256 <            return null;
257 <        elements[h] = null;     // Must null out slot
258 <        head = (h + 1) & (elements.length - 1);
255 >        if (result != null) {
256 >            elements[h] = null; // Must null out slot
257 >            head = (h + 1) & (elements.length - 1);
258 >        }
259          return result;
260      }
261  
262      public E pollLast() {
263 <        int t = (tail - 1) & (elements.length - 1);
263 >        final Object[] elements = this.elements;
264 >        final int t = (tail - 1) & (elements.length - 1);
265          @SuppressWarnings("unchecked")
266          E result = (E) elements[t];
267 <        if (result == null)
268 <            return null;
269 <        elements[t] = null;
270 <        tail = t;
267 >        if (result != null) {
268 >            elements[t] = null;
269 >            tail = t;
270 >        }
271          return result;
272      }
273  
# Line 361 | Line 317 | public class ArrayDeque<E> extends Abstr
317       * @return {@code true} if the deque contained the specified element
318       */
319      public boolean removeFirstOccurrence(Object o) {
320 <        if (o == null)
321 <            return false;
322 <        int mask = elements.length - 1;
323 <        int i = head;
324 <        Object x;
325 <        while ( (x = elements[i]) != null) {
326 <            if (o.equals(x)) {
327 <                delete(i);
372 <                return true;
320 >        if (o != null) {
321 >            int mask = elements.length - 1;
322 >            int i = head;
323 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
324 >                if (o.equals(x)) {
325 >                    delete(i);
326 >                    return true;
327 >                }
328              }
374            i = (i + 1) & mask;
329          }
330          return false;
331      }
# Line 389 | Line 343 | public class ArrayDeque<E> extends Abstr
343       * @return {@code true} if the deque contained the specified element
344       */
345      public boolean removeLastOccurrence(Object o) {
346 <        if (o == null)
347 <            return false;
348 <        int mask = elements.length - 1;
349 <        int i = (tail - 1) & mask;
350 <        Object x;
351 <        while ( (x = elements[i]) != null) {
352 <            if (o.equals(x)) {
353 <                delete(i);
400 <                return true;
346 >        if (o != null) {
347 >            int mask = elements.length - 1;
348 >            int i = (tail - 1) & mask;
349 >            for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
350 >                if (o.equals(x)) {
351 >                    delete(i);
352 >                    return true;
353 >                }
354              }
402            i = (i - 1) & mask;
355          }
356          return false;
357      }
# Line 536 | Line 488 | public class ArrayDeque<E> extends Abstr
488       *
489       * @return true if elements moved backwards
490       */
491 <    private boolean delete(int i) {
491 >    boolean delete(int i) {
492          checkInvariants();
493          final Object[] elements = this.elements;
494          final int mask = elements.length - 1;
# Line 656 | Line 608 | public class ArrayDeque<E> extends Abstr
608              }
609              lastRet = -1;
610          }
611 +
612 +        public void forEachRemaining(Consumer<? super E> action) {
613 +            Objects.requireNonNull(action);
614 +            Object[] a = elements;
615 +            int m = a.length - 1, f = fence, i = cursor;
616 +            cursor = f;
617 +            while (i != f) {
618 +                @SuppressWarnings("unchecked") E e = (E)a[i];
619 +                i = (i + 1) & m;
620 +                if (e == null)
621 +                    throw new ConcurrentModificationException();
622 +                action.accept(e);
623 +            }
624 +        }
625      }
626  
627 +    /**
628 +     * This class is nearly a mirror-image of DeqIterator, using tail
629 +     * instead of head for initial cursor, and head instead of tail
630 +     * for fence.
631 +     */
632      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         */
633          private int cursor = tail;
634          private int fence = head;
635          private int lastRet = -1;
# Line 704 | Line 670 | public class ArrayDeque<E> extends Abstr
670       * @return {@code true} if this deque contains the specified element
671       */
672      public boolean contains(Object o) {
673 <        if (o == null)
674 <            return false;
675 <        int mask = elements.length - 1;
676 <        int i = head;
677 <        Object x;
678 <        while ( (x = elements[i]) != null) {
679 <            if (o.equals(x))
714 <                return true;
715 <            i = (i + 1) & mask;
673 >        if (o != null) {
674 >            int mask = elements.length - 1;
675 >            int i = head;
676 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
677 >                if (o.equals(x))
678 >                    return true;
679 >            }
680          }
681          return false;
682      }
# Line 725 | Line 689 | public class ArrayDeque<E> extends Abstr
689       * Returns {@code true} if this deque contained the specified element
690       * (or equivalently, if this deque changed as a result of the call).
691       *
692 <     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
692 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
693       *
694       * @param o element to be removed from this deque, if present
695       * @return {@code true} if this deque contained the specified element
# Line 766 | Line 730 | public class ArrayDeque<E> extends Abstr
730       * @return an array containing all of the elements in this deque
731       */
732      public Object[] toArray() {
733 <        return copyElements(new Object[size()]);
733 >        final int head = this.head;
734 >        final int tail = this.tail;
735 >        boolean wrap = (tail < head);
736 >        int end = wrap ? tail + elements.length : tail;
737 >        Object[] a = Arrays.copyOfRange(elements, head, end);
738 >        if (wrap)
739 >            System.arraycopy(elements, 0, a, elements.length - head, tail);
740 >        return a;
741      }
742  
743      /**
# Line 791 | Line 762 | public class ArrayDeque<E> extends Abstr
762       * The following code can be used to dump the deque into a newly
763       * allocated array of {@code String}:
764       *
765 <     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
765 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
766       *
767       * Note that {@code toArray(new Object[0])} is identical in function to
768       * {@code toArray()}.
# Line 807 | Line 778 | public class ArrayDeque<E> extends Abstr
778       */
779      @SuppressWarnings("unchecked")
780      public <T> T[] toArray(T[] a) {
781 <        int size = size();
782 <        if (a.length < size)
783 <            a = (T[])java.lang.reflect.Array.newInstance(
784 <                    a.getClass().getComponentType(), size);
785 <        copyElements(a);
786 <        if (a.length > size)
787 <            a[size] = null;
781 >        final int head = this.head;
782 >        final int tail = this.tail;
783 >        boolean wrap = (tail < head);
784 >        int size = (tail - head) + (wrap ? elements.length : 0);
785 >        int firstLeg = size - (wrap ? tail : 0);
786 >        int len = a.length;
787 >        if (size > len) {
788 >            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
789 >                                         a.getClass());
790 >        } else {
791 >            System.arraycopy(elements, head, a, 0, firstLeg);
792 >            if (size < len)
793 >                a[size] = null;
794 >        }
795 >        if (wrap)
796 >            System.arraycopy(elements, 0, a, firstLeg, tail);
797          return a;
798      }
799  
# Line 840 | Line 820 | public class ArrayDeque<E> extends Abstr
820      /**
821       * Saves this deque to a stream (that is, serializes it).
822       *
823 +     * @param s the stream
824 +     * @throws java.io.IOException if an I/O error occurs
825       * @serialData The current size ({@code int}) of the deque,
826       * followed by all of its elements (each an object reference) in
827       * first-to-last order.
# Line 859 | Line 841 | public class ArrayDeque<E> extends Abstr
841  
842      /**
843       * Reconstitutes this deque from a stream (that is, deserializes it).
844 +     * @param s the stream
845 +     * @throws ClassNotFoundException if the class of a serialized object
846 +     *         could not be found
847 +     * @throws java.io.IOException if an I/O error occurs
848       */
849      private void readObject(java.io.ObjectInputStream s)
850              throws java.io.IOException, ClassNotFoundException {
# Line 875 | Line 861 | public class ArrayDeque<E> extends Abstr
861              elements[i] = s.readObject();
862      }
863  
864 <    public Stream<E> stream() {
865 <        int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_SIZED;
866 <        return Streams.stream
867 <            (() -> new DeqSpliterator<E>(this, head, tail), flags);
868 <    }
869 <    public Stream<E> parallelStream() {
870 <        int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_SIZED;
871 <        return Streams.parallelStream
872 <            (() -> new DeqSpliterator<E>(this, head, tail), flags);
864 >    /**
865 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
866 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
867 >     * deque.
868 >     *
869 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
870 >     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
871 >     * {@link Spliterator#NONNULL}.  Overriding implementations should document
872 >     * the reporting of additional characteristic values.
873 >     *
874 >     * @return a {@code Spliterator} over the elements in this deque
875 >     * @since 1.8
876 >     */
877 >    public Spliterator<E> spliterator() {
878 >        return new DeqSpliterator<>(this, -1, -1);
879      }
880  
881 <
890 <    static final class DeqSpliterator<E> implements Spliterator<E>, Iterator<E> {
881 >    static final class DeqSpliterator<E> implements Spliterator<E> {
882          private final ArrayDeque<E> deq;
883 <        private final Object[] array;
884 <        private final int fence;  // initially tail
894 <        private int index;        // current index, modified on traverse/split
883 >        private int fence;  // -1 until first use
884 >        private int index;  // current index, modified on traverse/split
885  
886 <        /** Create new spliterator covering the given array and range */
886 >        /** Creates new spliterator covering the given array and range. */
887          DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
888 <            this.deq = deq; this.array = deq.elements;
889 <            this.index = origin; this.fence = fence;
888 >            this.deq = deq;
889 >            this.index = origin;
890 >            this.fence = fence;
891 >        }
892 >
893 >        private int getFence() { // force initialization
894 >            int t;
895 >            if ((t = fence) < 0) {
896 >                t = fence = deq.tail;
897 >                index = deq.head;
898 >            }
899 >            return t;
900          }
901  
902          public DeqSpliterator<E> trySplit() {
903 <            int n = array.length;
904 <            int h = index, t = fence;
903 >            int t = getFence(), h = index, n = deq.elements.length;
904              if (h != t && ((h + 1) & (n - 1)) != t) {
905                  if (h > t)
906                      t += n;
# Line 911 | Line 910 | public class ArrayDeque<E> extends Abstr
910              return null;
911          }
912  
913 <        @SuppressWarnings("unchecked")
914 <        public void forEach(Block<? super E> block) {
916 <            if (block == null)
913 >        public void forEachRemaining(Consumer<? super E> consumer) {
914 >            if (consumer == null)
915                  throw new NullPointerException();
916 <            Object[] a = array;
917 <            if (a != deq.elements)
920 <                throw new ConcurrentModificationException();
921 <            int m = a.length - 1, f = fence, i = index;
916 >            Object[] a = deq.elements;
917 >            int m = a.length - 1, f = getFence(), i = index;
918              index = f;
919              while (i != f) {
920 <                Object e = a[i];
920 >                @SuppressWarnings("unchecked") E e = (E)a[i];
921 >                i = (i + 1) & m;
922                  if (e == null)
923                      throw new ConcurrentModificationException();
924 <                block.accept((E)e);
928 <                i = (i + 1) & m;
924 >                consumer.accept(e);
925              }
926          }
927  
928 <        @SuppressWarnings("unchecked")
929 <        public boolean tryAdvance(Block<? super E> block) {
934 <            if (block == null)
928 >        public boolean tryAdvance(Consumer<? super E> consumer) {
929 >            if (consumer == null)
930                  throw new NullPointerException();
931 <            Object[] a = array;
932 <            if (a != deq.elements)
933 <                throw new ConcurrentModificationException();
934 <            int m = a.length - 1, i = index;
935 <            if (i != fence) {
941 <                Object e = a[i];
931 >            Object[] a = deq.elements;
932 >            int m = a.length - 1, f = getFence(), i = index;
933 >            if (i != f) {
934 >                @SuppressWarnings("unchecked") E e = (E)a[i];
935 >                index = (i + 1) & m;
936                  if (e == null)
937                      throw new ConcurrentModificationException();
938 <                block.accept((E)e);
945 <                index = (i + 1) & m;
938 >                consumer.accept(e);
939                  return true;
940              }
941              return false;
942          }
943  
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
944          public long estimateSize() {
945 <            int n = fence - index;
945 >            int n = getFence() - index;
946              if (n < 0)
947 <                n += array.length;
948 <            return (long)n;
947 >                n += deq.elements.length;
948 >            return (long) n;
949 >        }
950 >
951 >        @Override
952 >        public int characteristics() {
953 >            return Spliterator.ORDERED | Spliterator.SIZED |
954 >                Spliterator.NONNULL | Spliterator.SUBSIZED;
955          }
983        public boolean hasExactSize() { return true; }
984        public boolean hasExactSplits() { return true; }
956      }
957  
958   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines