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.65 by jsr166, Sat Feb 28 20:35:47 2015 UTC vs.
Revision 1.105 by jsr166, Tue Nov 1 21:42:45 2016 UTC

# Line 7 | Line 7 | package java.util;
7  
8   import java.io.Serializable;
9   import java.util.function.Consumer;
10 + import java.util.function.Predicate;
11 + import java.util.function.UnaryOperator;
12  
13   /**
14   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 52 | Line 54 | import java.util.function.Consumer;
54   * Java Collections Framework</a>.
55   *
56   * @author  Josh Bloch and Doug Lea
55 * @since   1.6
57   * @param <E> the type of elements held in this deque
58 + * @since   1.6
59   */
60   public class ArrayDeque<E> extends AbstractCollection<E>
61                             implements Deque<E>, Cloneable, Serializable
62   {
63      /**
64       * The array in which the elements of the deque are stored.
65 <     * The capacity of the deque is the length of this array, which is
66 <     * always a power of two. The array is never allowed to become
65 <     * full, except transiently within an addX method where it is
66 <     * resized (see doubleCapacity) immediately upon becoming full,
67 <     * thus avoiding head and tail wrapping around to equal each
68 <     * other.  We also guarantee that all array cells not holding
69 <     * deque elements are always null.
65 >     * We guarantee that all array cells not holding deque elements
66 >     * are always null.
67       */
68 <    transient Object[] elements; // non-private to simplify nested class access
68 >    transient Object[] elements;
69  
70      /**
71       * The index of the element at the head of the deque (which is the
72       * element that would be removed by remove() or pop()); or an
73 <     * arbitrary number equal to tail if the deque is empty.
73 >     * arbitrary number 0 <= head < elements.length if the deque is empty.
74       */
75      transient int head;
76  
77 +    /** Number of elements in this collection. */
78 +    transient int size;
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)).
81 >     * The maximum size of array to allocate.
82 >     * Some VMs reserve some header words in an array.
83 >     * Attempts to allocate larger arrays may result in
84 >     * OutOfMemoryError: Requested array size exceeds VM limit
85       */
86 <    transient int tail;
86 >    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
87  
88      /**
89 <     * The minimum capacity that we'll use for a newly created deque.
90 <     * Must be a power of 2.
89 >     * Increases the capacity of this deque by at least the given amount.
90 >     *
91 >     * @param needed the required minimum extra capacity; must be positive
92       */
93 <    private static final int MIN_INITIAL_CAPACITY = 8;
93 >    private Object[] grow(int needed) {
94 >        // overflow-conscious code
95 >        // checkInvariants();
96 >        final int oldCapacity = elements.length;
97 >        int newCapacity;
98 >        // Double size if small; else grow by 50%
99 >        int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
100 >        if (jump < needed
101 >            || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
102 >            newCapacity = newCapacity(needed, jump);
103 >        elements = Arrays.copyOf(elements, newCapacity);
104 >        if (oldCapacity - head < size) {
105 >            // wrap around; slide first leg forward to end of array
106 >            int newSpace = newCapacity - oldCapacity;
107 >            System.arraycopy(elements, head,
108 >                             elements, head + newSpace,
109 >                             oldCapacity - head);
110 >            Arrays.fill(elements, head, head + newSpace, null);
111 >            head += newSpace;
112 >        }
113 >        return elements;
114 >        // checkInvariants();
115 >    }
116  
117 <    // ******  Array allocation and resizing utilities ******
117 >    /** Capacity calculation for edge conditions, especially overflow. */
118 >    private int newCapacity(int needed, int jump) {
119 >        final int oldCapacity = elements.length, minCapacity;
120 >        if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
121 >            if (minCapacity < 0)
122 >                throw new IllegalStateException("Sorry, deque too big");
123 >            return Integer.MAX_VALUE;
124 >        }
125 >        if (needed > jump)
126 >            return minCapacity;
127 >        return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
128 >            ? oldCapacity + jump
129 >            : MAX_ARRAY_SIZE;
130 >    }
131  
132      /**
133 <     * Allocates empty array to hold the given number of elements.
133 >     * Increases the internal storage of this collection, if necessary,
134 >     * to ensure that it can hold at least the given number of elements.
135       *
136 <     * @param numElements  the number of elements to hold
136 >     * @param minCapacity the desired minimum capacity
137 >     * @since TBD
138       */
139 <    private void allocateElements(int numElements) {
140 <        int initialCapacity = MIN_INITIAL_CAPACITY;
141 <        // Find the best power of two to hold elements.
142 <        // Tests "<=" because arrays aren't kept full.
103 <        if (numElements >= initialCapacity) {
104 <            initialCapacity = numElements;
105 <            initialCapacity |= (initialCapacity >>>  1);
106 <            initialCapacity |= (initialCapacity >>>  2);
107 <            initialCapacity |= (initialCapacity >>>  4);
108 <            initialCapacity |= (initialCapacity >>>  8);
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
114 <        }
115 <        elements = new Object[initialCapacity];
139 >    /* public */ void ensureCapacity(int minCapacity) {
140 >        if (minCapacity > elements.length)
141 >            grow(minCapacity - elements.length);
142 >        // checkInvariants();
143      }
144  
145      /**
146 <     * Doubles the capacity of this deque.  Call only when full, i.e.,
147 <     * when head and tail have wrapped around to become equal.
146 >     * Minimizes the internal storage of this collection.
147 >     *
148 >     * @since TBD
149       */
150 <    private void doubleCapacity() {
151 <        assert head == tail;
152 <        int p = head;
153 <        int n = elements.length;
154 <        int r = n - p; // number of elements to the right of p
155 <        int newCapacity = n << 1;
128 <        if (newCapacity < 0)
129 <            throw new IllegalStateException("Sorry, deque too big");
130 <        Object[] a = new Object[newCapacity];
131 <        System.arraycopy(elements, p, a, 0, r);
132 <        System.arraycopy(elements, 0, a, r, p);
133 <        elements = a;
134 <        head = 0;
135 <        tail = n;
150 >    /* public */ void trimToSize() {
151 >        if (size < elements.length) {
152 >            elements = toArray();
153 >            head = 0;
154 >        }
155 >        // checkInvariants();
156      }
157  
158      /**
# Line 147 | Line 167 | public class ArrayDeque<E> extends Abstr
167       * Constructs an empty array deque with an initial capacity
168       * sufficient to hold the specified number of elements.
169       *
170 <     * @param numElements  lower bound on initial capacity of the deque
170 >     * @param numElements lower bound on initial capacity of the deque
171       */
172      public ArrayDeque(int numElements) {
173 <        allocateElements(numElements);
173 >        elements = new Object[numElements];
174      }
175  
176      /**
# Line 164 | Line 184 | public class ArrayDeque<E> extends Abstr
184       * @throws NullPointerException if the specified collection is null
185       */
186      public ArrayDeque(Collection<? extends E> c) {
187 <        allocateElements(c.size());
188 <        addAll(c);
187 >        Object[] es = c.toArray();
188 >        // defend against c.toArray (incorrectly) not returning Object[]
189 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
190 >        if (es.getClass() != Object[].class)
191 >            es = Arrays.copyOf(es, es.length, Object[].class);
192 >        for (Object obj : es)
193 >            Objects.requireNonNull(obj);
194 >        this.elements = es;
195 >        this.size = es.length;
196 >    }
197 >
198 >    /**
199 >     * Increments i, mod modulus.
200 >     * Precondition and postcondition: 0 <= i < modulus.
201 >     */
202 >    static final int inc(int i, int modulus) {
203 >        if (++i >= modulus) i = 0;
204 >        return i;
205 >    }
206 >
207 >    /**
208 >     * Decrements i, mod modulus.
209 >     * Precondition and postcondition: 0 <= i < modulus.
210 >     */
211 >    static final int dec(int i, int modulus) {
212 >        if (--i < 0) i = modulus - 1;
213 >        return i;
214 >    }
215 >
216 >    /**
217 >     * Adds i and j, mod modulus.
218 >     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
219 >     */
220 >    static final int add(int i, int j, int modulus) {
221 >        if ((i += j) - modulus >= 0) i -= modulus;
222 >        return i;
223 >    }
224 >
225 >    /**
226 >     * Returns the array index of the last element.
227 >     * May return invalid index -1 if there are no elements.
228 >     */
229 >    final int tail() {
230 >        return add(head, size - 1, elements.length);
231 >    }
232 >
233 >    /**
234 >     * Returns element at array index i.
235 >     */
236 >    @SuppressWarnings("unchecked")
237 >    private E elementAt(int i) {
238 >        return (E) elements[i];
239 >    }
240 >
241 >    /**
242 >     * A version of elementAt that checks for null elements.
243 >     * This check doesn't catch all possible comodifications,
244 >     * but does catch ones that corrupt traversal.  It's a little
245 >     * surprising that javac allows this abuse of generics.
246 >     */
247 >    static final <E> E nonNullElementAt(Object[] es, int i) {
248 >        @SuppressWarnings("unchecked") E e = (E) es[i];
249 >        if (e == null)
250 >            throw new ConcurrentModificationException();
251 >        return e;
252      }
253  
254      // The main insertion and extraction methods are addFirst,
# Line 179 | Line 262 | public class ArrayDeque<E> extends Abstr
262       * @throws NullPointerException if the specified element is null
263       */
264      public void addFirst(E e) {
265 <        if (e == null)
266 <            throw new NullPointerException();
267 <        elements[head = (head - 1) & (elements.length - 1)] = e;
268 <        if (head == tail)
269 <            doubleCapacity();
265 >        // checkInvariants();
266 >        Objects.requireNonNull(e);
267 >        Object[] es;
268 >        int capacity, h;
269 >        final int s;
270 >        if ((s = size) == (capacity = (es = elements).length))
271 >            capacity = (es = grow(1)).length;
272 >        if ((h = head - 1) < 0) h = capacity - 1;
273 >        es[head = h] = e;
274 >        size = s + 1;
275 >        // checkInvariants();
276      }
277  
278      /**
# Line 195 | Line 284 | public class ArrayDeque<E> extends Abstr
284       * @throws NullPointerException if the specified element is null
285       */
286      public void addLast(E e) {
287 <        if (e == null)
288 <            throw new NullPointerException();
289 <        elements[tail] = e;
290 <        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
291 <            doubleCapacity();
287 >        // checkInvariants();
288 >        Objects.requireNonNull(e);
289 >        Object[] es;
290 >        int capacity;
291 >        final int s;
292 >        if ((s = size) == (capacity = (es = elements).length))
293 >            capacity = (es = grow(1)).length;
294 >        es[add(head, s, capacity)] = e;
295 >        size = s + 1;
296 >        // checkInvariants();
297 >    }
298 >
299 >    /**
300 >     * Adds all of the elements in the specified collection at the end
301 >     * of this deque, as if by calling {@link #addLast} on each one,
302 >     * in the order that they are returned by the collection's
303 >     * iterator.
304 >     *
305 >     * @param c the elements to be inserted into this deque
306 >     * @return {@code true} if this deque changed as a result of the call
307 >     * @throws NullPointerException if the specified collection or any
308 >     *         of its elements are null
309 >     */
310 >    public boolean addAll(Collection<? extends E> c) {
311 >        final int s = size, needed = c.size() - (elements.length - s);
312 >        if (needed > 0)
313 >            grow(needed);
314 >        c.forEach((e) -> addLast(e));
315 >        // checkInvariants();
316 >        return size > s;
317      }
318  
319      /**
# Line 230 | Line 344 | public class ArrayDeque<E> extends Abstr
344       * @throws NoSuchElementException {@inheritDoc}
345       */
346      public E removeFirst() {
347 <        E x = pollFirst();
348 <        if (x == null)
347 >        // checkInvariants();
348 >        E e = pollFirst();
349 >        if (e == null)
350              throw new NoSuchElementException();
351 <        return x;
351 >        return e;
352      }
353  
354      /**
355       * @throws NoSuchElementException {@inheritDoc}
356       */
357      public E removeLast() {
358 <        E x = pollLast();
359 <        if (x == null)
358 >        // checkInvariants();
359 >        E e = pollLast();
360 >        if (e == null)
361              throw new NoSuchElementException();
362 <        return x;
362 >        return e;
363      }
364  
365      public E pollFirst() {
366 <        int h = head;
367 <        @SuppressWarnings("unchecked")
368 <        E result = (E) elements[h];
369 <        // Element is null if deque empty
370 <        if (result != null) {
371 <            elements[h] = null; // Must null out slot
372 <            head = (h + 1) & (elements.length - 1);
373 <        }
374 <        return result;
366 >        // checkInvariants();
367 >        int s, h;
368 >        if ((s = size) <= 0)
369 >            return null;
370 >        final Object[] es = elements;
371 >        @SuppressWarnings("unchecked") E e = (E) es[h = head];
372 >        es[h] = null;
373 >        if (++h >= es.length) h = 0;
374 >        head = h;
375 >        size = s - 1;
376 >        return e;
377      }
378  
379      public E pollLast() {
380 <        int t = (tail - 1) & (elements.length - 1);
380 >        // checkInvariants();
381 >        final int s, tail;
382 >        if ((s = size) <= 0)
383 >            return null;
384 >        final Object[] es = elements;
385          @SuppressWarnings("unchecked")
386 <        E result = (E) elements[t];
387 <        if (result != null) {
388 <            elements[t] = null;
389 <            tail = t;
268 <        }
269 <        return result;
386 >        E e = (E) es[tail = add(head, s - 1, es.length)];
387 >        es[tail] = null;
388 >        size = s - 1;
389 >        return e;
390      }
391  
392      /**
393       * @throws NoSuchElementException {@inheritDoc}
394       */
395      public E getFirst() {
396 <        @SuppressWarnings("unchecked")
397 <        E result = (E) elements[head];
398 <        if (result == null)
279 <            throw new NoSuchElementException();
280 <        return result;
396 >        // checkInvariants();
397 >        if (size <= 0) throw new NoSuchElementException();
398 >        return elementAt(head);
399      }
400  
401      /**
402       * @throws NoSuchElementException {@inheritDoc}
403       */
404 +    @SuppressWarnings("unchecked")
405      public E getLast() {
406 <        @SuppressWarnings("unchecked")
407 <        E result = (E) elements[(tail - 1) & (elements.length - 1)];
408 <        if (result == null)
409 <            throw new NoSuchElementException();
410 <        return result;
406 >        // checkInvariants();
407 >        final int s;
408 >        if ((s = size) <= 0) throw new NoSuchElementException();
409 >        final Object[] es = elements;
410 >        return (E) es[add(head, s - 1, es.length)];
411      }
412  
294    @SuppressWarnings("unchecked")
413      public E peekFirst() {
414 <        // elements[head] is null if deque empty
415 <        return (E) elements[head];
414 >        // checkInvariants();
415 >        return (size <= 0) ? null : elementAt(head);
416      }
417  
418      @SuppressWarnings("unchecked")
419      public E peekLast() {
420 <        return (E) elements[(tail - 1) & (elements.length - 1)];
420 >        // checkInvariants();
421 >        final int s;
422 >        if ((s = size) <= 0) return null;
423 >        final Object[] es = elements;
424 >        return (E) es[add(head, s - 1, es.length)];
425      }
426  
427      /**
# Line 316 | Line 438 | public class ArrayDeque<E> extends Abstr
438       */
439      public boolean removeFirstOccurrence(Object o) {
440          if (o != null) {
441 <            int mask = elements.length - 1;
442 <            int i = head;
443 <            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
444 <                if (o.equals(x)) {
445 <                    delete(i);
446 <                    return true;
447 <                }
441 >            final Object[] es = elements;
442 >            int i, end, to, todo;
443 >            todo = (end = (i = head) + size)
444 >                - (to = (es.length - end >= 0) ? end : es.length);
445 >            for (;; to = todo, todo = 0, i = 0) {
446 >                for (; i < to; i++)
447 >                    if (o.equals(es[i])) {
448 >                        delete(i);
449 >                        return true;
450 >                    }
451 >                if (todo == 0) break;
452              }
453          }
454          return false;
# Line 342 | Line 468 | public class ArrayDeque<E> extends Abstr
468       */
469      public boolean removeLastOccurrence(Object o) {
470          if (o != null) {
471 <            int mask = elements.length - 1;
472 <            int i = (tail - 1) & mask;
473 <            for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
474 <                if (o.equals(x)) {
475 <                    delete(i);
476 <                    return true;
477 <                }
471 >            final Object[] es = elements;
472 >            int i, to, end, todo;
473 >            todo = (to = ((end = (i = tail()) - size) >= -1) ? end : -1) - end;
474 >            for (;; to = (i = es.length - 1) - todo, todo = 0) {
475 >                for (; i > to; i--)
476 >                    if (o.equals(es[i])) {
477 >                        delete(i);
478 >                        return true;
479 >                    }
480 >                if (todo == 0) break;
481              }
482          }
483          return false;
# Line 468 | Line 597 | public class ArrayDeque<E> extends Abstr
597          return removeFirst();
598      }
599  
471    private void checkInvariants() {
472        assert elements[tail] == null;
473        assert head == tail ? elements[head] == null :
474            (elements[head] != null &&
475             elements[(tail - 1) & (elements.length - 1)] != null);
476        assert elements[(head - 1) & (elements.length - 1)] == null;
477    }
478
600      /**
601 <     * Removes the element at the specified position in the elements array,
602 <     * adjusting head and tail as necessary.  This can result in motion of
603 <     * elements backwards or forwards in the array.
601 >     * Removes the element at the specified position in the elements array.
602 >     * This can result in forward or backwards motion of array elements.
603 >     * We optimize for least element motion.
604       *
605       * <p>This method is called delete rather than remove to emphasize
606       * that its semantics differ from those of {@link List#remove(int)}.
607       *
608       * @return true if elements moved backwards
609       */
610 <    private boolean delete(int i) {
611 <        checkInvariants();
612 <        final Object[] elements = this.elements;
613 <        final int mask = elements.length - 1;
610 >    boolean delete(int i) {
611 >        // checkInvariants();
612 >        final Object[] es = elements;
613 >        final int capacity = es.length;
614          final int h = head;
615 <        final int t = tail;
616 <        final int front = (i - h) & mask;
617 <        final int back  = (t - i) & mask;
497 <
498 <        // Invariant: head <= i < tail mod circularity
499 <        if (front >= ((t - h) & mask))
500 <            throw new ConcurrentModificationException();
501 <
502 <        // Optimize for least element motion
615 >        int front;              // number of elements before to-be-deleted elt
616 >        if ((front = i - h) < 0) front += capacity;
617 >        final int back = size - front - 1; // number of elements after
618          if (front < back) {
619 +            // move front elements forwards
620              if (h <= i) {
621 <                System.arraycopy(elements, h, elements, h + 1, front);
621 >                System.arraycopy(es, h, es, h + 1, front);
622              } else { // Wrap around
623 <                System.arraycopy(elements, 0, elements, 1, i);
624 <                elements[0] = elements[mask];
625 <                System.arraycopy(elements, h, elements, h + 1, mask - h);
623 >                System.arraycopy(es, 0, es, 1, i);
624 >                es[0] = es[capacity - 1];
625 >                System.arraycopy(es, h, es, h + 1, front - (i + 1));
626              }
627 <            elements[h] = null;
628 <            head = (h + 1) & mask;
627 >            es[h] = null;
628 >            if ((head = (h + 1)) >= capacity) head = 0;
629 >            size--;
630 >            // checkInvariants();
631              return false;
632          } else {
633 <            if (i < t) { // Copy the null tail as well
634 <                System.arraycopy(elements, i + 1, elements, i, back);
635 <                tail = t - 1;
633 >            // move back elements backwards
634 >            int tail = tail();
635 >            if (i <= tail) {
636 >                System.arraycopy(es, i + 1, es, i, back);
637              } else { // Wrap around
638 <                System.arraycopy(elements, i + 1, elements, i, mask - i);
639 <                elements[mask] = elements[0];
640 <                System.arraycopy(elements, 1, elements, 0, t);
641 <                tail = (t - 1) & mask;
638 >                int firstLeg = capacity - (i + 1);
639 >                System.arraycopy(es, i + 1, es, i, firstLeg);
640 >                es[capacity - 1] = es[0];
641 >                System.arraycopy(es, 1, es, 0, back - firstLeg - 1);
642              }
643 +            es[tail] = null;
644 +            size--;
645 +            // checkInvariants();
646              return true;
647          }
648      }
# Line 533 | Line 655 | public class ArrayDeque<E> extends Abstr
655       * @return the number of elements in this deque
656       */
657      public int size() {
658 <        return (tail - head) & (elements.length - 1);
658 >        return size;
659      }
660  
661      /**
# Line 542 | Line 664 | public class ArrayDeque<E> extends Abstr
664       * @return {@code true} if this deque contains no elements
665       */
666      public boolean isEmpty() {
667 <        return head == tail;
667 >        return size == 0;
668      }
669  
670      /**
# Line 562 | Line 684 | public class ArrayDeque<E> extends Abstr
684      }
685  
686      private class DeqIterator implements Iterator<E> {
687 <        /**
688 <         * Index of element to be returned by subsequent call to next.
567 <         */
568 <        private int cursor = head;
687 >        /** Index of element to be returned by subsequent call to next. */
688 >        int cursor;
689  
690 <        /**
691 <         * Tail recorded at construction (also in remove), to stop
572 <         * iterator and also to check for comodification.
573 <         */
574 <        private int fence = tail;
690 >        /** Number of elements yet to be returned. */
691 >        int remaining = size;
692  
693          /**
694           * Index of element returned by most recent call to next.
695           * Reset to -1 if element is deleted by a call to remove.
696           */
697 <        private int lastRet = -1;
697 >        int lastRet = -1;
698 >
699 >        DeqIterator() { cursor = head; }
700  
701 <        public boolean hasNext() {
702 <            return cursor != fence;
701 >        public final boolean hasNext() {
702 >            return remaining > 0;
703          }
704  
705          public E next() {
706 <            if (cursor == fence)
706 >            if (remaining <= 0)
707                  throw new NoSuchElementException();
708 <            @SuppressWarnings("unchecked")
709 <            E result = (E) elements[cursor];
591 <            // This check doesn't catch all possible comodifications,
592 <            // but does catch the ones that corrupt traversal
593 <            if (tail != fence || result == null)
594 <                throw new ConcurrentModificationException();
708 >            final Object[] es = elements;
709 >            E e = nonNullElementAt(es, cursor);
710              lastRet = cursor;
711 <            cursor = (cursor + 1) & (elements.length - 1);
712 <            return result;
711 >            if (++cursor >= es.length) cursor = 0;
712 >            remaining--;
713 >            return e;
714 >        }
715 >
716 >        void postDelete(boolean leftShifted) {
717 >            if (leftShifted)
718 >                if (--cursor < 0) cursor = elements.length - 1;
719          }
720  
721 <        public void remove() {
721 >        public final void remove() {
722              if (lastRet < 0)
723                  throw new IllegalStateException();
724 <            if (delete(lastRet)) { // if left-shifted, undo increment in next()
604 <                cursor = (cursor - 1) & (elements.length - 1);
605 <                fence = tail;
606 <            }
724 >            postDelete(delete(lastRet));
725              lastRet = -1;
726          }
727 +
728 +        public void forEachRemaining(Consumer<? super E> action) {
729 +            Objects.requireNonNull(action);
730 +            final int k;
731 +            if ((k = remaining) > 0) {
732 +                remaining = 0;
733 +                ArrayDeque.forEachRemaining(action, elements, cursor, k);
734 +                if ((lastRet = cursor + k - 1) >= elements.length)
735 +                    lastRet -= elements.length;
736 +            }
737 +        }
738 +    }
739 +
740 +    private class DescendingIterator extends DeqIterator {
741 +        DescendingIterator() { cursor = tail(); }
742 +
743 +        public final E next() {
744 +            if (remaining <= 0)
745 +                throw new NoSuchElementException();
746 +            final Object[] es = elements;
747 +            E e = nonNullElementAt(es, cursor);
748 +            lastRet = cursor;
749 +            if (--cursor < 0) cursor = es.length - 1;
750 +            remaining--;
751 +            return e;
752 +        }
753 +
754 +        void postDelete(boolean leftShifted) {
755 +            if (!leftShifted)
756 +                if (++cursor >= elements.length) cursor = 0;
757 +        }
758 +
759 +        public final void forEachRemaining(Consumer<? super E> action) {
760 +            Objects.requireNonNull(action);
761 +            final int k;
762 +            if ((k = remaining) > 0) {
763 +                remaining = 0;
764 +                final Object[] es = elements;
765 +                int i, end, to, todo;
766 +                todo = (to = ((end = (i = cursor) - k) >= -1) ? end : -1) - end;
767 +                for (;; to = (i = es.length - 1) - todo, todo = 0) {
768 +                    for (; i > to; i--)
769 +                        action.accept(nonNullElementAt(es, i));
770 +                    if (todo == 0) break;
771 +                }
772 +                if ((lastRet = cursor - (k - 1)) < 0)
773 +                    lastRet += es.length;
774 +            }
775 +        }
776      }
777  
778      /**
779 <     * This class is nearly a mirror-image of DeqIterator, using tail
780 <     * instead of head for initial cursor, and head instead of tail
781 <     * for fence.
782 <     */
783 <    private class DescendingIterator implements Iterator<E> {
784 <        private int cursor = tail;
785 <        private int fence = head;
786 <        private int lastRet = -1;
779 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
780 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
781 >     * deque.
782 >     *
783 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
784 >     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
785 >     * {@link Spliterator#NONNULL}.  Overriding implementations should document
786 >     * the reporting of additional characteristic values.
787 >     *
788 >     * @return a {@code Spliterator} over the elements in this deque
789 >     * @since 1.8
790 >     */
791 >    public Spliterator<E> spliterator() {
792 >        return new ArrayDequeSpliterator();
793 >    }
794 >
795 >    final class ArrayDequeSpliterator implements Spliterator<E> {
796 >        private int cursor;
797 >        private int remaining; // -1 until late-binding first use
798  
799 <        public boolean hasNext() {
800 <            return cursor != fence;
799 >        /** Constructs late-binding spliterator over all elements. */
800 >        ArrayDequeSpliterator() {
801 >            this.remaining = -1;
802          }
803  
804 <        public E next() {
805 <            if (cursor == fence)
806 <                throw new NoSuchElementException();
807 <            cursor = (cursor - 1) & (elements.length - 1);
629 <            @SuppressWarnings("unchecked")
630 <            E result = (E) elements[cursor];
631 <            if (head != fence || result == null)
632 <                throw new ConcurrentModificationException();
633 <            lastRet = cursor;
634 <            return result;
804 >        /** Constructs spliterator over the given slice. */
805 >        ArrayDequeSpliterator(int cursor, int count) {
806 >            this.cursor = cursor;
807 >            this.remaining = count;
808          }
809  
810 <        public void remove() {
811 <            if (lastRet < 0)
812 <                throw new IllegalStateException();
813 <            if (!delete(lastRet)) {
814 <                cursor = (cursor + 1) & (elements.length - 1);
642 <                fence = head;
810 >        /** Ensures late-binding initialization; then returns remaining. */
811 >        private int remaining() {
812 >            if (remaining < 0) {
813 >                cursor = head;
814 >                remaining = size;
815              }
816 <            lastRet = -1;
816 >            return remaining;
817 >        }
818 >
819 >        public ArrayDequeSpliterator trySplit() {
820 >            final int mid;
821 >            if ((mid = remaining() >> 1) > 0) {
822 >                int oldCursor = cursor;
823 >                cursor = add(cursor, mid, elements.length);
824 >                remaining -= mid;
825 >                return new ArrayDequeSpliterator(oldCursor, mid);
826 >            }
827 >            return null;
828 >        }
829 >
830 >        public void forEachRemaining(Consumer<? super E> action) {
831 >            Objects.requireNonNull(action);
832 >            final int k = remaining(); // side effect!
833 >            remaining = 0;
834 >            ArrayDeque.forEachRemaining(action, elements, cursor, k);
835 >        }
836 >
837 >        public boolean tryAdvance(Consumer<? super E> action) {
838 >            Objects.requireNonNull(action);
839 >            final int k;
840 >            if ((k = remaining()) <= 0)
841 >                return false;
842 >            action.accept(nonNullElementAt(elements, cursor));
843 >            if (++cursor >= elements.length) cursor = 0;
844 >            remaining = k - 1;
845 >            return true;
846 >        }
847 >
848 >        public long estimateSize() {
849 >            return remaining();
850 >        }
851 >
852 >        public int characteristics() {
853 >            return Spliterator.NONNULL
854 >                | Spliterator.ORDERED
855 >                | Spliterator.SIZED
856 >                | Spliterator.SUBSIZED;
857 >        }
858 >    }
859 >
860 >    @SuppressWarnings("unchecked")
861 >    public void forEach(Consumer<? super E> action) {
862 >        Objects.requireNonNull(action);
863 >        final Object[] es = elements;
864 >        int i, end, to, todo;
865 >        todo = (end = (i = head) + size)
866 >            - (to = (es.length - end >= 0) ? end : es.length);
867 >        for (;; to = todo, todo = 0, i = 0) {
868 >            for (; i < to; i++)
869 >                action.accept((E) es[i]);
870 >            if (todo == 0) break;
871 >        }
872 >        // checkInvariants();
873 >    }
874 >
875 >    /**
876 >     * Calls action on remaining elements, starting at index i and
877 >     * traversing in ascending order.  A variant of forEach that also
878 >     * checks for concurrent modification, for use in iterators.
879 >     */
880 >    static <E> void forEachRemaining(
881 >        Consumer<? super E> action, Object[] es, int i, int remaining) {
882 >        int end, to, todo;
883 >        todo = (end = i + remaining)
884 >            - (to = (es.length - end >= 0) ? end : es.length);
885 >        for (;; to = todo, todo = 0, i = 0) {
886 >            for (; i < to; i++)
887 >                action.accept(nonNullElementAt(es, i));
888 >            if (todo == 0) break;
889 >        }
890 >    }
891 >
892 >    /**
893 >     * Replaces each element of this deque with the result of applying the
894 >     * operator to that element, as specified by {@link List#replaceAll}.
895 >     *
896 >     * @param operator the operator to apply to each element
897 >     * @since TBD
898 >     */
899 >    @SuppressWarnings("unchecked")
900 >    /* public */ void replaceAll(UnaryOperator<E> operator) {
901 >        Objects.requireNonNull(operator);
902 >        final Object[] es = elements;
903 >        int i, end, to, todo;
904 >        todo = (end = (i = head) + size)
905 >            - (to = (es.length - end >= 0) ? end : es.length);
906 >        for (;; to = todo, todo = 0, i = 0) {
907 >            for (; i < to; i++)
908 >                es[i] = operator.apply((E) es[i]);
909 >            if (todo == 0) break;
910 >        }
911 >        // checkInvariants();
912 >    }
913 >
914 >    /**
915 >     * @throws NullPointerException {@inheritDoc}
916 >     */
917 >    public boolean removeIf(Predicate<? super E> filter) {
918 >        Objects.requireNonNull(filter);
919 >        return bulkRemove(filter);
920 >    }
921 >
922 >    /**
923 >     * @throws NullPointerException {@inheritDoc}
924 >     */
925 >    public boolean removeAll(Collection<?> c) {
926 >        Objects.requireNonNull(c);
927 >        return bulkRemove(e -> c.contains(e));
928 >    }
929 >
930 >    /**
931 >     * @throws NullPointerException {@inheritDoc}
932 >     */
933 >    public boolean retainAll(Collection<?> c) {
934 >        Objects.requireNonNull(c);
935 >        return bulkRemove(e -> !c.contains(e));
936 >    }
937 >
938 >    /** Implementation of bulk remove methods. */
939 >    @SuppressWarnings("unchecked")
940 >    private boolean bulkRemove(Predicate<? super E> filter) {
941 >        // checkInvariants();
942 >        final Object[] es = elements;
943 >        int i, end, to, todo;
944 >        todo = (end = (i = head) + size)
945 >            - (to = (es.length - end >= 0) ? end : es.length);
946 >        // Optimize for initial run of non-removed elements
947 >        findFirstRemoved:
948 >        for (;; to = todo, todo = 0, i = 0) {
949 >            for (; i < to; i++)
950 >                if (filter.test((E) es[i]))
951 >                    break findFirstRemoved;
952 >            if (todo == 0) return false;
953          }
954 +        bulkRemoveModified(filter, i, to, todo);
955 +        return true;
956 +    }
957 +
958 +    /**
959 +     * Helper for bulkRemove, in case of at least one deletion.
960 +     * @param i valid index of first element to be deleted
961 +     */
962 +    @SuppressWarnings("unchecked")
963 +    private void bulkRemoveModified(
964 +        Predicate<? super E> filter, int i, int to, int todo) {
965 +        final Object[] es = elements;
966 +        final int capacity = es.length;
967 +        // a two-finger algorithm, with hare i and tortoise j
968 +        int j = i++;
969 +        try {
970 +            for (;;) {
971 +                E e;
972 +                // In this loop, i and j are on the same leg, with i > j
973 +                for (; i < to; i++)
974 +                    if (!filter.test(e = (E) es[i]))
975 +                        es[j++] = e;
976 +                if (todo == 0) break;
977 +                // In this loop, j is on the first leg, i on the second
978 +                for (to = todo, todo = 0, i = 0; i < to && j < capacity; i++)
979 +                    if (!filter.test(e = (E) es[i]))
980 +                        es[j++] = e;
981 +                if (i >= to) break;
982 +                j = 0;          // j rejoins i on second leg
983 +            }
984 +            bulkRemoveClear(es, j, i);
985 +            // checkInvariants();
986 +        } catch (Throwable ex) {
987 +            // copy remaining elements
988 +            for (int remaining = (to - i) + todo; --remaining >= 0;) {
989 +                es[j] = es[i];
990 +                if (++i >= capacity) i = 0;
991 +                if (++j >= capacity) j = 0;
992 +            }
993 +            bulkRemoveClear(es, j, i);
994 +            // checkInvariants();
995 +            throw ex;
996 +        }
997 +    }
998 +
999 +    /**
1000 +     * Nulls out all elements from index j upto index i.
1001 +     */
1002 +    private void bulkRemoveClear(Object[] es, int j, int i) {
1003 +        int deleted;
1004 +        if ((deleted = i - j) <= 0) deleted += es.length;
1005 +        size -= deleted;
1006 +        circularClear(es, j, deleted);
1007      }
1008  
1009      /**
# Line 655 | Line 1016 | public class ArrayDeque<E> extends Abstr
1016       */
1017      public boolean contains(Object o) {
1018          if (o != null) {
1019 <            int mask = elements.length - 1;
1020 <            int i = head;
1021 <            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
1022 <                if (o.equals(x))
1023 <                    return true;
1019 >            final Object[] es = elements;
1020 >            int i, end, to, todo;
1021 >            todo = (end = (i = head) + size)
1022 >                - (to = (es.length - end >= 0) ? end : es.length);
1023 >            for (;; to = todo, todo = 0, i = 0) {
1024 >                for (; i < to; i++)
1025 >                    if (o.equals(es[i]))
1026 >                        return true;
1027 >                if (todo == 0) break;
1028              }
1029          }
1030          return false;
# Line 687 | Line 1052 | public class ArrayDeque<E> extends Abstr
1052       * The deque will be empty after this call returns.
1053       */
1054      public void clear() {
1055 <        int h = head;
1056 <        int t = tail;
1057 <        if (h != t) { // clear all cells
1058 <            head = tail = 0;
1059 <            int i = h;
1060 <            int mask = elements.length - 1;
1061 <            do {
1062 <                elements[i] = null;
1063 <                i = (i + 1) & mask;
1064 <            } while (i != t);
1055 >        circularClear(elements, head, size);
1056 >        size = head = 0;
1057 >        // checkInvariants();
1058 >    }
1059 >
1060 >    /**
1061 >     * Nulls out count elements, starting at array index from.
1062 >     * Special case (from == es.length) is treated the same as (from == 0).
1063 >     */
1064 >    private static void circularClear(Object[] es, int from, int count) {
1065 >        int end, to, todo;
1066 >        todo = (end = from + count)
1067 >            - (to = (es.length - end >= 0) ? end : es.length);
1068 >        for (;; to = todo, todo = 0, from = 0) {
1069 >            Arrays.fill(es, from, to, null);
1070 >            if (todo == 0) break;
1071          }
1072      }
1073  
# Line 714 | Line 1085 | public class ArrayDeque<E> extends Abstr
1085       * @return an array containing all of the elements in this deque
1086       */
1087      public Object[] toArray() {
1088 <        final int head = this.head;
1089 <        final int tail = this.tail;
1090 <        boolean wrap = (tail < head);
1091 <        int end = wrap ? tail + elements.length : tail;
1092 <        Object[] a = Arrays.copyOfRange(elements, head, end);
1093 <        if (wrap)
1094 <            System.arraycopy(elements, 0, a, elements.length - head, tail);
1088 >        return toArray(Object[].class);
1089 >    }
1090 >
1091 >    private <T> T[] toArray(Class<T[]> klazz) {
1092 >        final Object[] es = elements;
1093 >        final T[] a;
1094 >        final int head, len, end, todo;
1095 >        todo = size - (len = Math.min(size, es.length - (head = this.head)));
1096 >        if ((end = head + size) >= 0) {
1097 >            a = Arrays.copyOfRange(es, head, end, klazz);
1098 >        } else {
1099 >            // integer overflow!
1100 >            a = Arrays.copyOfRange(es, 0, size, klazz);
1101 >            System.arraycopy(es, head, a, 0, len);
1102 >        }
1103 >        if (todo > 0)
1104 >            System.arraycopy(es, 0, a, len, todo);
1105          return a;
1106      }
1107  
# Line 762 | Line 1143 | public class ArrayDeque<E> extends Abstr
1143       */
1144      @SuppressWarnings("unchecked")
1145      public <T> T[] toArray(T[] a) {
1146 <        final int head = this.head;
1147 <        final int tail = this.tail;
1148 <        boolean wrap = (tail < head);
1149 <        int size = (tail - head) + (wrap ? elements.length : 0);
1150 <        int firstLeg = size - (wrap ? tail : 0);
1151 <        int len = a.length;
1152 <        if (size > len) {
1153 <            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
1154 <                                         a.getClass());
774 <        } else {
775 <            System.arraycopy(elements, head, a, 0, firstLeg);
776 <            if (size < len)
777 <                a[size] = null;
1146 >        final int size;
1147 >        if ((size = this.size) > a.length)
1148 >            return toArray((Class<T[]>) a.getClass());
1149 >        final Object[] es = elements;
1150 >        int i, j, len, todo;
1151 >        todo = size - (len = Math.min(size, es.length - (i = head)));
1152 >        for (j = 0;; j += len, len = todo, todo = 0, i = 0) {
1153 >            System.arraycopy(es, i, a, j, len);
1154 >            if (todo == 0) break;
1155          }
1156 <        if (wrap)
1157 <            System.arraycopy(elements, 0, a, firstLeg, tail);
1156 >        if (size < a.length)
1157 >            a[size] = null;
1158          return a;
1159      }
1160  
# Line 815 | Line 1192 | public class ArrayDeque<E> extends Abstr
1192          s.defaultWriteObject();
1193  
1194          // Write out size
1195 <        s.writeInt(size());
1195 >        s.writeInt(size);
1196  
1197          // Write out elements in order.
1198 <        int mask = elements.length - 1;
1199 <        for (int i = head; i != tail; i = (i + 1) & mask)
1200 <            s.writeObject(elements[i]);
1198 >        final Object[] es = elements;
1199 >        int i, end, to, todo;
1200 >        todo = (end = (i = head) + size)
1201 >            - (to = (es.length - end >= 0) ? end : es.length);
1202 >        for (;; to = todo, todo = 0, i = 0) {
1203 >            for (; i < to; i++)
1204 >                s.writeObject(es[i]);
1205 >            if (todo == 0) break;
1206 >        }
1207      }
1208  
1209      /**
# Line 835 | Line 1218 | public class ArrayDeque<E> extends Abstr
1218          s.defaultReadObject();
1219  
1220          // Read in size and allocate array
1221 <        int size = s.readInt();
839 <        allocateElements(size);
840 <        head = 0;
841 <        tail = size;
1221 >        elements = new Object[size = s.readInt()];
1222  
1223          // Read in all elements in the proper order.
1224          for (int i = 0; i < size; i++)
1225              elements[i] = s.readObject();
1226      }
1227  
1228 <    public Spliterator<E> spliterator() {
1229 <        return new DeqSpliterator<E>(this, -1, -1);
1230 <    }
1231 <
1232 <    static final class DeqSpliterator<E> implements Spliterator<E> {
1233 <        private final ArrayDeque<E> deq;
1234 <        private int fence;  // -1 until first use
1235 <        private int index;  // current index, modified on traverse/split
1236 <
1237 <        /** Creates new spliterator covering the given array and range */
1238 <        DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
1239 <            this.deq = deq;
1240 <            this.index = origin;
1241 <            this.fence = fence;
1242 <        }
1243 <
1244 <        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 != f) {
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;
1228 >    /** debugging */
1229 >    void checkInvariants() {
1230 >        try {
1231 >            int capacity = elements.length;
1232 >            // assert size >= 0 && size <= capacity;
1233 >            // assert head >= 0;
1234 >            // assert capacity == 0 || head < capacity;
1235 >            // assert size == 0 || elements[head] != null;
1236 >            // assert size == 0 || elements[tail()] != null;
1237 >            // assert size == capacity || elements[dec(head, capacity)] == null;
1238 >            // assert size == capacity || elements[inc(tail(), capacity)] == null;
1239 >        } catch (Throwable t) {
1240 >            System.err.printf("head=%d size=%d capacity=%d%n",
1241 >                              head, size, elements.length);
1242 >            System.err.printf("elements=%s%n",
1243 >                              Arrays.toString(elements));
1244 >            throw t;
1245          }
1246      }
1247  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines