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.47 by dl, Sun Feb 17 23:36:16 2013 UTC vs.
Revision 1.67 by jsr166, Thu Sep 10 00:05:48 2015 UTC

# Line 4 | Line 4
4   */
5  
6   package java.util;
7 +
8   import java.io.Serializable;
9   import java.util.function.Consumer;
9 import java.util.stream.Stream;
10 import java.util.stream.Streams;
10  
11   /**
12   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 19 | Line 18 | import java.util.stream.Streams;
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.
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 {@code iterator} 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 {@code remove}
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 52 | Line 53 | import java.util.stream.Streams;
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, Serializable
# Line 135 | Line 136 | public class ArrayDeque<E> extends Abstr
136      }
137  
138      /**
138     * Copies the elements from our element array into the specified array,
139     * in order (from first to last element in the deque).  It is assumed
140     * that the array is large enough to hold all elements in the deque.
141     *
142     * @return its argument
143     */
144    private <T> T[] copyElements(T[] a) {
145        if (head < tail) {
146            System.arraycopy(elements, head, a, 0, size());
147        } else if (head > tail) {
148            int headPortionLen = elements.length - head;
149            System.arraycopy(elements, head, a, 0, headPortionLen);
150            System.arraycopy(elements, 0, a, headPortionLen, tail);
151        }
152        return a;
153    }
154
155    /**
139       * Constructs an empty array deque with an initial capacity
140       * sufficient to hold 16 elements.
141       */
# Line 264 | 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 332 | 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);
343 <                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              }
345            i = (i + 1) & mask;
329          }
330          return false;
331      }
# Line 360 | 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);
371 <                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              }
373            i = (i - 1) & mask;
355          }
356          return false;
357      }
# Line 629 | Line 610 | public class ArrayDeque<E> extends Abstr
610          }
611      }
612  
613 +    /**
614 +     * This class is nearly a mirror-image of DeqIterator, using tail
615 +     * instead of head for initial cursor, and head instead of tail
616 +     * for fence.
617 +     */
618      private class DescendingIterator implements Iterator<E> {
633        /*
634         * This class is nearly a mirror-image of DeqIterator, using
635         * tail instead of head for initial cursor, and head instead of
636         * tail for fence.
637         */
619          private int cursor = tail;
620          private int fence = head;
621          private int lastRet = -1;
# Line 675 | Line 656 | public class ArrayDeque<E> extends Abstr
656       * @return {@code true} if this deque contains the specified element
657       */
658      public boolean contains(Object o) {
659 <        if (o == null)
660 <            return false;
661 <        int mask = elements.length - 1;
662 <        int i = head;
663 <        Object x;
664 <        while ( (x = elements[i]) != null) {
665 <            if (o.equals(x))
685 <                return true;
686 <            i = (i + 1) & mask;
659 >        if (o != null) {
660 >            int mask = elements.length - 1;
661 >            int i = head;
662 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
663 >                if (o.equals(x))
664 >                    return true;
665 >            }
666          }
667          return false;
668      }
# Line 737 | Line 716 | public class ArrayDeque<E> extends Abstr
716       * @return an array containing all of the elements in this deque
717       */
718      public Object[] toArray() {
719 <        return copyElements(new Object[size()]);
719 >        final int head = this.head;
720 >        final int tail = this.tail;
721 >        boolean wrap = (tail < head);
722 >        int end = wrap ? tail + elements.length : tail;
723 >        Object[] a = Arrays.copyOfRange(elements, head, end);
724 >        if (wrap)
725 >            System.arraycopy(elements, 0, a, elements.length - head, tail);
726 >        return a;
727      }
728  
729      /**
# Line 762 | Line 748 | public class ArrayDeque<E> extends Abstr
748       * The following code can be used to dump the deque into a newly
749       * allocated array of {@code String}:
750       *
751 <     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
751 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
752       *
753       * Note that {@code toArray(new Object[0])} is identical in function to
754       * {@code toArray()}.
# Line 778 | Line 764 | public class ArrayDeque<E> extends Abstr
764       */
765      @SuppressWarnings("unchecked")
766      public <T> T[] toArray(T[] a) {
767 <        int size = size();
768 <        if (a.length < size)
769 <            a = (T[])java.lang.reflect.Array.newInstance(
770 <                    a.getClass().getComponentType(), size);
771 <        copyElements(a);
772 <        if (a.length > size)
773 <            a[size] = null;
767 >        final int head = this.head;
768 >        final int tail = this.tail;
769 >        boolean wrap = (tail < head);
770 >        int size = (tail - head) + (wrap ? elements.length : 0);
771 >        int firstLeg = size - (wrap ? tail : 0);
772 >        int len = a.length;
773 >        if (size > len) {
774 >            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
775 >                                         a.getClass());
776 >        } else {
777 >            System.arraycopy(elements, head, a, 0, firstLeg);
778 >            if (size < len)
779 >                a[size] = null;
780 >        }
781 >        if (wrap)
782 >            System.arraycopy(elements, 0, a, firstLeg, tail);
783          return a;
784      }
785  
# Line 811 | Line 806 | public class ArrayDeque<E> extends Abstr
806      /**
807       * Saves this deque to a stream (that is, serializes it).
808       *
809 +     * @param s the stream
810 +     * @throws java.io.IOException if an I/O error occurs
811       * @serialData The current size ({@code int}) of the deque,
812       * followed by all of its elements (each an object reference) in
813       * first-to-last order.
# Line 830 | Line 827 | public class ArrayDeque<E> extends Abstr
827  
828      /**
829       * Reconstitutes this deque from a stream (that is, deserializes it).
830 +     * @param s the stream
831 +     * @throws ClassNotFoundException if the class of a serialized object
832 +     *         could not be found
833 +     * @throws java.io.IOException if an I/O error occurs
834       */
835      private void readObject(java.io.ObjectInputStream s)
836              throws java.io.IOException, ClassNotFoundException {
# Line 846 | Line 847 | public class ArrayDeque<E> extends Abstr
847              elements[i] = s.readObject();
848      }
849  
850 <    Spliterator<E> spliterator() {
851 <        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());
850 >    public Spliterator<E> spliterator() {
851 >        return new DeqSpliterator<>(this, -1, -1);
852      }
853  
854      static final class DeqSpliterator<E> implements Spliterator<E> {
855          private final ArrayDeque<E> deq;
856          private int fence;  // -1 until first use
857          private int index;  // current index, modified on traverse/split
858 <        
859 <        /** Create new spliterator covering the given array and range */
858 >
859 >        /** Creates new spliterator covering the given array and range */
860          DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
861              this.deq = deq;
862              this.index = origin;
# Line 879 | Line 872 | public class ArrayDeque<E> extends Abstr
872              return t;
873          }
874  
875 <        public DeqSpliterator<E> trySplit() {
875 >        public Spliterator<E> trySplit() {
876              int t = getFence(), h = index, n = deq.elements.length;
877              if (h != t && ((h + 1) & (n - 1)) != t) {
878                  if (h > t)
# Line 890 | Line 883 | public class ArrayDeque<E> extends Abstr
883              return null;
884          }
885  
886 <        public void forEach(Consumer<? super E> consumer) {
886 >        public void forEachRemaining(Consumer<? super E> consumer) {
887              if (consumer == null)
888                  throw new NullPointerException();
889              Object[] a = deq.elements;
# Line 910 | Line 903 | public class ArrayDeque<E> extends Abstr
903                  throw new NullPointerException();
904              Object[] a = deq.elements;
905              int m = a.length - 1, f = getFence(), i = index;
906 <            if (i != fence) {
906 >            if (i != f) {
907                  @SuppressWarnings("unchecked") E e = (E)a[i];
908                  index = (i + 1) & m;
909                  if (e == null)
# Line 930 | Line 923 | public class ArrayDeque<E> extends Abstr
923  
924          @Override
925          public int characteristics() {
926 <            return Spliterator.ORDERED | Spliterator.SIZED |
926 >            return Spliterator.ORDERED | Spliterator.SIZED |
927                  Spliterator.NONNULL | Spliterator.SUBSIZED;
928          }
929      }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines