ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/ArrayDeque.java
(Generate patch)

Comparing jsr166/src/jdk8/java/util/ArrayDeque.java (file contents):
Revision 1.1 by jsr166, Sat Mar 26 06:22:49 2016 UTC vs.
Revision 1.2 by jsr166, Mon Oct 24 23:54:10 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 void grow(int needed) {
94 >        // overflow-conscious code
95 >        // checkInvariants();
96 >        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 >        // checkInvariants();
114 >    }
115  
116 <    // ******  Array allocation and resizing utilities ******
116 >    /** Capacity calculation for edge conditions, especially overflow. */
117 >    private int newCapacity(int needed, int jump) {
118 >        int oldCapacity = elements.length;
119 >        int 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[] elements = c.toArray();
188 >        // defend against c.toArray (incorrectly) not returning Object[]
189 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
190 >        size = elements.length;
191 >        if (elements.getClass() != Object[].class)
192 >            elements = Arrays.copyOf(elements, size, Object[].class);
193 >        for (Object obj : elements)
194 >            Objects.requireNonNull(obj);
195 >        this.elements = elements;
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.
245 >     */
246 >    E checkedElementAt(Object[] elements, int i) {
247 >        @SuppressWarnings("unchecked") E e = (E) elements[i];
248 >        if (e == null)
249 >            throw new ConcurrentModificationException();
250 >        return e;
251      }
252  
253      // The main insertion and extraction methods are addFirst,
# Line 179 | Line 261 | public class ArrayDeque<E> extends Abstr
261       * @throws NullPointerException if the specified element is null
262       */
263      public void addFirst(E e) {
264 <        if (e == null)
265 <            throw new NullPointerException();
266 <        elements[head = (head - 1) & (elements.length - 1)] = e;
267 <        if (head == tail)
268 <            doubleCapacity();
264 >        // checkInvariants();
265 >        Objects.requireNonNull(e);
266 >        Object[] elements;
267 >        int capacity, h;
268 >        final int s;
269 >        if ((s = size) == (capacity = (elements = this.elements).length)) {
270 >            grow(1);
271 >            capacity = (elements = this.elements).length;
272 >        }
273 >        if ((h = head - 1) < 0) h = capacity - 1;
274 >        elements[head = h] = e;
275 >        size = s + 1;
276 >        // checkInvariants();
277      }
278  
279      /**
# Line 195 | Line 285 | public class ArrayDeque<E> extends Abstr
285       * @throws NullPointerException if the specified element is null
286       */
287      public void addLast(E e) {
288 <        if (e == null)
289 <            throw new NullPointerException();
290 <        elements[tail] = e;
291 <        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
292 <            doubleCapacity();
288 >        // checkInvariants();
289 >        Objects.requireNonNull(e);
290 >        Object[] elements;
291 >        int capacity;
292 >        final int s;
293 >        if ((s = size) == (capacity = (elements = this.elements).length)) {
294 >            grow(1);
295 >            capacity = (elements = this.elements).length;
296 >        }
297 >        elements[add(head, s, capacity)] = e;
298 >        size = s + 1;
299 >        // checkInvariants();
300 >    }
301 >
302 >    /**
303 >     * Adds all of the elements in the specified collection at the end
304 >     * of this deque, as if by calling {@link #addLast} on each one,
305 >     * in the order that they are returned by the collection's
306 >     * iterator.
307 >     *
308 >     * @param c the elements to be inserted into this deque
309 >     * @return {@code true} if this deque changed as a result of the call
310 >     * @throws NullPointerException if the specified collection or any
311 >     *         of its elements are null
312 >     */
313 >    public boolean addAll(Collection<? extends E> c) {
314 >        final int s = size, needed = c.size() - (elements.length - s);
315 >        if (needed > 0)
316 >            grow(needed);
317 >        c.forEach((e) -> addLast(e));
318 >        // checkInvariants();
319 >        return size > s;
320      }
321  
322      /**
# Line 230 | Line 347 | public class ArrayDeque<E> extends Abstr
347       * @throws NoSuchElementException {@inheritDoc}
348       */
349      public E removeFirst() {
350 <        E x = pollFirst();
351 <        if (x == null)
350 >        // checkInvariants();
351 >        E e = pollFirst();
352 >        if (e == null)
353              throw new NoSuchElementException();
354 <        return x;
354 >        return e;
355      }
356  
357      /**
358       * @throws NoSuchElementException {@inheritDoc}
359       */
360      public E removeLast() {
361 <        E x = pollLast();
362 <        if (x == null)
361 >        // checkInvariants();
362 >        E e = pollLast();
363 >        if (e == null)
364              throw new NoSuchElementException();
365 <        return x;
365 >        return e;
366      }
367  
368      public E pollFirst() {
369 +        // checkInvariants();
370 +        int s, h;
371 +        if ((s = size) == 0)
372 +            return null;
373          final Object[] elements = this.elements;
374 <        final int h = head;
375 <        @SuppressWarnings("unchecked")
376 <        E result = (E) elements[h];
377 <        // Element is null if deque empty
378 <        if (result != null) {
379 <            elements[h] = null; // Must null out slot
257 <            head = (h + 1) & (elements.length - 1);
258 <        }
259 <        return result;
374 >        @SuppressWarnings("unchecked") E e = (E) elements[h = head];
375 >        elements[h] = null;
376 >        if (++h >= elements.length) h = 0;
377 >        head = h;
378 >        size = s - 1;
379 >        return e;
380      }
381  
382      public E pollLast() {
383 +        // checkInvariants();
384 +        final int s, tail;
385 +        if ((s = size) == 0)
386 +            return null;
387          final Object[] elements = this.elements;
264        final int t = (tail - 1) & (elements.length - 1);
388          @SuppressWarnings("unchecked")
389 <        E result = (E) elements[t];
390 <        if (result != null) {
391 <            elements[t] = null;
392 <            tail = t;
270 <        }
271 <        return result;
389 >        E e = (E) elements[tail = add(head, s - 1, elements.length)];
390 >        elements[tail] = null;
391 >        size = s - 1;
392 >        return e;
393      }
394  
395      /**
396       * @throws NoSuchElementException {@inheritDoc}
397       */
398      public E getFirst() {
399 <        @SuppressWarnings("unchecked")
400 <        E result = (E) elements[head];
401 <        if (result == null)
281 <            throw new NoSuchElementException();
282 <        return result;
399 >        // checkInvariants();
400 >        if (size == 0) throw new NoSuchElementException();
401 >        return elementAt(head);
402      }
403  
404      /**
405       * @throws NoSuchElementException {@inheritDoc}
406       */
407      public E getLast() {
408 <        @SuppressWarnings("unchecked")
409 <        E result = (E) elements[(tail - 1) & (elements.length - 1)];
410 <        if (result == null)
292 <            throw new NoSuchElementException();
293 <        return result;
408 >        // checkInvariants();
409 >        if (size == 0) throw new NoSuchElementException();
410 >        return elementAt(tail());
411      }
412  
296    @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  
302    @SuppressWarnings("unchecked")
418      public E peekLast() {
419 <        return (E) elements[(tail - 1) & (elements.length - 1)];
419 >        // checkInvariants();
420 >        return (size == 0) ? null : elementAt(tail());
421      }
422  
423      /**
# Line 318 | Line 434 | public class ArrayDeque<E> extends Abstr
434       */
435      public boolean removeFirstOccurrence(Object o) {
436          if (o != null) {
437 <            int mask = elements.length - 1;
438 <            int i = head;
439 <            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
440 <                if (o.equals(x)) {
441 <                    delete(i);
442 <                    return true;
443 <                }
437 >            final Object[] elements = this.elements;
438 >            final int capacity = elements.length;
439 >            int from, end, to, leftover;
440 >            leftover = (end = (from = head) + size)
441 >                - (to = (capacity - end >= 0) ? end : capacity);
442 >            for (;; from = 0, to = leftover, leftover = 0) {
443 >                for (int i = from; i < to; i++)
444 >                    if (o.equals(elements[i])) {
445 >                        delete(i);
446 >                        return true;
447 >                    }
448 >                if (leftover == 0) break;
449              }
450          }
451          return false;
# Line 344 | Line 465 | public class ArrayDeque<E> extends Abstr
465       */
466      public boolean removeLastOccurrence(Object o) {
467          if (o != null) {
468 <            int mask = elements.length - 1;
469 <            int i = (tail - 1) & mask;
470 <            for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
471 <                if (o.equals(x)) {
472 <                    delete(i);
473 <                    return true;
474 <                }
468 >            final Object[] elements = this.elements;
469 >            final int capacity = elements.length;
470 >            int from, to, end, leftover;
471 >            leftover = (to = ((end = (from = tail()) - size) >= -1) ? end : -1) - end;
472 >            for (;; from = capacity - 1, to = capacity - 1 - leftover, leftover = 0) {
473 >                for (int i = from; i > to; i--)
474 >                    if (o.equals(elements[i])) {
475 >                        delete(i);
476 >                        return true;
477 >                    }
478 >                if (leftover == 0) break;
479              }
480          }
481          return false;
# Line 470 | Line 595 | public class ArrayDeque<E> extends Abstr
595          return removeFirst();
596      }
597  
473    private void checkInvariants() {
474        assert elements[tail] == null;
475        assert head == tail ? elements[head] == null :
476            (elements[head] != null &&
477             elements[(tail - 1) & (elements.length - 1)] != null);
478        assert elements[(head - 1) & (elements.length - 1)] == null;
479    }
480
598      /**
599 <     * Removes the element at the specified position in the elements array,
600 <     * adjusting head and tail as necessary.  This can result in motion of
601 <     * elements backwards or forwards in the array.
599 >     * Removes the element at the specified position in the elements array.
600 >     * This can result in forward or backwards motion of array elements.
601 >     * We optimize for least element motion.
602       *
603       * <p>This method is called delete rather than remove to emphasize
604       * that its semantics differ from those of {@link List#remove(int)}.
# Line 489 | Line 606 | public class ArrayDeque<E> extends Abstr
606       * @return true if elements moved backwards
607       */
608      boolean delete(int i) {
609 <        checkInvariants();
609 >        // checkInvariants();
610          final Object[] elements = this.elements;
611 <        final int mask = elements.length - 1;
611 >        final int capacity = elements.length;
612          final int h = head;
613 <        final int t = tail;
614 <        final int front = (i - h) & mask;
615 <        final int back  = (t - i) & mask;
499 <
500 <        // Invariant: head <= i < tail mod circularity
501 <        if (front >= ((t - h) & mask))
502 <            throw new ConcurrentModificationException();
503 <
504 <        // Optimize for least element motion
613 >        int front;              // number of elements before to-be-deleted elt
614 >        if ((front = i - h) < 0) front += capacity;
615 >        final int back = size - front - 1; // number of elements after
616          if (front < back) {
617 +            // move front elements forwards
618              if (h <= i) {
619                  System.arraycopy(elements, h, elements, h + 1, front);
620              } else { // Wrap around
621                  System.arraycopy(elements, 0, elements, 1, i);
622 <                elements[0] = elements[mask];
623 <                System.arraycopy(elements, h, elements, h + 1, mask - h);
622 >                elements[0] = elements[capacity - 1];
623 >                System.arraycopy(elements, h, elements, h + 1, front - (i + 1));
624              }
625              elements[h] = null;
626 <            head = (h + 1) & mask;
626 >            if ((head = (h + 1)) >= capacity) head = 0;
627 >            size--;
628 >            // checkInvariants();
629              return false;
630          } else {
631 <            if (i < t) { // Copy the null tail as well
631 >            // move back elements backwards
632 >            int tail = tail();
633 >            if (i <= tail) {
634                  System.arraycopy(elements, i + 1, elements, i, back);
519                tail = t - 1;
635              } else { // Wrap around
636 <                System.arraycopy(elements, i + 1, elements, i, mask - i);
637 <                elements[mask] = elements[0];
638 <                System.arraycopy(elements, 1, elements, 0, t);
639 <                tail = (t - 1) & mask;
636 >                int firstLeg = capacity - (i + 1);
637 >                System.arraycopy(elements, i + 1, elements, i, firstLeg);
638 >                elements[capacity - 1] = elements[0];
639 >                System.arraycopy(elements, 1, elements, 0, back - firstLeg - 1);
640              }
641 +            elements[tail] = null;
642 +            size--;
643 +            // checkInvariants();
644              return true;
645          }
646      }
# Line 535 | Line 653 | public class ArrayDeque<E> extends Abstr
653       * @return the number of elements in this deque
654       */
655      public int size() {
656 <        return (tail - head) & (elements.length - 1);
656 >        return size;
657      }
658  
659      /**
# Line 544 | Line 662 | public class ArrayDeque<E> extends Abstr
662       * @return {@code true} if this deque contains no elements
663       */
664      public boolean isEmpty() {
665 <        return head == tail;
665 >        return size == 0;
666      }
667  
668      /**
# Line 564 | Line 682 | public class ArrayDeque<E> extends Abstr
682      }
683  
684      private class DeqIterator implements Iterator<E> {
685 <        /**
686 <         * Index of element to be returned by subsequent call to next.
569 <         */
570 <        private int cursor = head;
685 >        /** Index of element to be returned by subsequent call to next. */
686 >        int cursor;
687  
688 <        /**
689 <         * Tail recorded at construction (also in remove), to stop
574 <         * iterator and also to check for comodification.
575 <         */
576 <        private int fence = tail;
688 >        /** Number of elements yet to be returned. */
689 >        int remaining = size;
690  
691          /**
692           * Index of element returned by most recent call to next.
693           * Reset to -1 if element is deleted by a call to remove.
694           */
695 <        private int lastRet = -1;
695 >        int lastRet = -1;
696 >
697 >        DeqIterator() { cursor = head; }
698  
699 <        public boolean hasNext() {
700 <            return cursor != fence;
699 >        public final boolean hasNext() {
700 >            return remaining > 0;
701          }
702  
703          public E next() {
704 <            if (cursor == fence)
704 >            if (remaining == 0)
705                  throw new NoSuchElementException();
706 <            @SuppressWarnings("unchecked")
707 <            E result = (E) elements[cursor];
593 <            // This check doesn't catch all possible comodifications,
594 <            // but does catch the ones that corrupt traversal
595 <            if (tail != fence || result == null)
596 <                throw new ConcurrentModificationException();
706 >            final Object[] elements = ArrayDeque.this.elements;
707 >            E e = checkedElementAt(elements, cursor);
708              lastRet = cursor;
709 <            cursor = (cursor + 1) & (elements.length - 1);
710 <            return result;
709 >            if (++cursor >= elements.length) cursor = 0;
710 >            remaining--;
711 >            return e;
712 >        }
713 >
714 >        void postDelete(boolean leftShifted) {
715 >            if (leftShifted)
716 >                if (--cursor < 0) cursor = elements.length - 1;
717          }
718  
719 <        public void remove() {
719 >        public final void remove() {
720              if (lastRet < 0)
721                  throw new IllegalStateException();
722 <            if (delete(lastRet)) { // if left-shifted, undo increment in next()
606 <                cursor = (cursor - 1) & (elements.length - 1);
607 <                fence = tail;
608 <            }
722 >            postDelete(delete(lastRet));
723              lastRet = -1;
724          }
725  
726          public void forEachRemaining(Consumer<? super E> action) {
727 +            int k;
728 +            if ((k = remaining) > 0) {
729 +                remaining = 0;
730 +                ArrayDeque.forEachRemaining(action, elements, cursor, k);
731 +                if ((lastRet = cursor + k - 1) >= elements.length)
732 +                    lastRet -= elements.length;
733 +            }
734 +        }
735 +    }
736 +
737 +    private class DescendingIterator extends DeqIterator {
738 +        DescendingIterator() { cursor = tail(); }
739 +
740 +        public final E next() {
741 +            if (remaining == 0)
742 +                throw new NoSuchElementException();
743 +            final Object[] elements = ArrayDeque.this.elements;
744 +            E e = checkedElementAt(elements, cursor);
745 +            lastRet = cursor;
746 +            if (--cursor < 0) cursor = elements.length - 1;
747 +            remaining--;
748 +            return e;
749 +        }
750 +
751 +        void postDelete(boolean leftShifted) {
752 +            if (!leftShifted)
753 +                if (++cursor >= elements.length) cursor = 0;
754 +        }
755 +
756 +        public final void forEachRemaining(Consumer<? super E> action) {
757 +            int k;
758 +            if ((k = remaining) > 0) {
759 +                remaining = 0;
760 +                forEachRemainingDescending(action, elements, cursor, k);
761 +                if ((lastRet = cursor - (k - 1)) < 0)
762 +                    lastRet += elements.length;
763 +            }
764 +        }
765 +    }
766 +
767 +    /**
768 +     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
769 +     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
770 +     * deque.
771 +     *
772 +     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
773 +     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
774 +     * {@link Spliterator#NONNULL}.  Overriding implementations should document
775 +     * the reporting of additional characteristic values.
776 +     *
777 +     * @return a {@code Spliterator} over the elements in this deque
778 +     * @since 1.8
779 +     */
780 +    public Spliterator<E> spliterator() {
781 +        return new ArrayDequeSpliterator();
782 +    }
783 +
784 +    final class ArrayDequeSpliterator implements Spliterator<E> {
785 +        private int cursor;
786 +        private int remaining; // -1 until late-binding first use
787 +
788 +        /** Constructs late-binding spliterator over all elements. */
789 +        ArrayDequeSpliterator() {
790 +            this.remaining = -1;
791 +        }
792 +
793 +        /** Constructs spliterator over the given slice. */
794 +        ArrayDequeSpliterator(int cursor, int count) {
795 +            this.cursor = cursor;
796 +            this.remaining = count;
797 +        }
798 +
799 +        /** Ensures late-binding initialization; then returns remaining. */
800 +        private int remaining() {
801 +            if (remaining < 0) {
802 +                cursor = head;
803 +                remaining = size;
804 +            }
805 +            return remaining;
806 +        }
807 +
808 +        public ArrayDequeSpliterator trySplit() {
809 +            final int mid;
810 +            if ((mid = remaining() >> 1) > 0) {
811 +                int oldCursor = cursor;
812 +                cursor = add(cursor, mid, elements.length);
813 +                remaining -= mid;
814 +                return new ArrayDequeSpliterator(oldCursor, mid);
815 +            }
816 +            return null;
817 +        }
818 +
819 +        public void forEachRemaining(Consumer<? super E> action) {
820 +            int k = remaining(); // side effect!
821 +            remaining = 0;
822 +            ArrayDeque.forEachRemaining(action, elements, cursor, k);
823 +        }
824 +
825 +        public boolean tryAdvance(Consumer<? super E> action) {
826              Objects.requireNonNull(action);
827 <            Object[] a = elements;
828 <            int m = a.length - 1, f = fence, i = cursor;
829 <            cursor = f;
830 <            while (i != f) {
831 <                @SuppressWarnings("unchecked") E e = (E)a[i];
832 <                i = (i + 1) & m;
827 >            if (remaining() == 0)
828 >                return false;
829 >            action.accept(checkedElementAt(elements, cursor));
830 >            if (++cursor >= elements.length) cursor = 0;
831 >            remaining--;
832 >            return true;
833 >        }
834 >
835 >        public long estimateSize() {
836 >            return remaining();
837 >        }
838 >
839 >        public int characteristics() {
840 >            return Spliterator.NONNULL
841 >                | Spliterator.ORDERED
842 >                | Spliterator.SIZED
843 >                | Spliterator.SUBSIZED;
844 >        }
845 >    }
846 >
847 >    @SuppressWarnings("unchecked")
848 >    public void forEach(Consumer<? super E> action) {
849 >        Objects.requireNonNull(action);
850 >        final Object[] elements = this.elements;
851 >        final int capacity = elements.length;
852 >        int from, end, to, leftover;
853 >        leftover = (end = (from = head) + size)
854 >            - (to = (capacity - end >= 0) ? end : capacity);
855 >        for (;; from = 0, to = leftover, leftover = 0) {
856 >            for (int i = from; i < to; i++)
857 >                action.accept((E) elements[i]);
858 >            if (leftover == 0) break;
859 >        }
860 >        // checkInvariants();
861 >    }
862 >
863 >    /**
864 >     * A variant of forEach that also checks for concurrent
865 >     * modification, for use in iterators.
866 >     */
867 >    static <E> void forEachRemaining(
868 >        Consumer<? super E> action, Object[] elements, int from, int size) {
869 >        Objects.requireNonNull(action);
870 >        final int capacity = elements.length;
871 >        int end, to, leftover;
872 >        leftover = (end = from + size)
873 >            - (to = (capacity - end >= 0) ? end : capacity);
874 >        for (;; from = 0, to = leftover, leftover = 0) {
875 >            for (int i = from; i < to; i++) {
876 >                @SuppressWarnings("unchecked") E e = (E) elements[i];
877                  if (e == null)
878                      throw new ConcurrentModificationException();
879                  action.accept(e);
880              }
881 +            if (leftover == 0) break;
882          }
883      }
884  
885 <    /**
886 <     * This class is nearly a mirror-image of DeqIterator, using tail
887 <     * instead of head for initial cursor, and head instead of tail
888 <     * for fence.
889 <     */
890 <    private class DescendingIterator implements Iterator<E> {
891 <        private int cursor = tail;
892 <        private int fence = head;
893 <        private int lastRet = -1;
894 <
895 <        public boolean hasNext() {
896 <            return cursor != fence;
885 >    static <E> void forEachRemainingDescending(
886 >        Consumer<? super E> action, Object[] elements, int from, int size) {
887 >        Objects.requireNonNull(action);
888 >        final int capacity = elements.length;
889 >        int end, to, leftover;
890 >        leftover = (to = ((end = from - size) >= -1) ? end : -1) - end;
891 >        for (;; from = capacity - 1, to = capacity - 1 - leftover, leftover = 0) {
892 >            for (int i = from; i > to; i--) {
893 >                @SuppressWarnings("unchecked") E e = (E) elements[i];
894 >                if (e == null)
895 >                    throw new ConcurrentModificationException();
896 >                action.accept(e);
897 >            }
898 >            if (leftover == 0) break;
899          }
900 +    }
901  
902 <        public E next() {
903 <            if (cursor == fence)
904 <                throw new NoSuchElementException();
905 <            cursor = (cursor - 1) & (elements.length - 1);
906 <            @SuppressWarnings("unchecked")
907 <            E result = (E) elements[cursor];
908 <            if (head != fence || result == null)
909 <                throw new ConcurrentModificationException();
910 <            lastRet = cursor;
911 <            return result;
902 >    /**
903 >     * Replaces each element of this deque with the result of applying the
904 >     * operator to that element, as specified by {@link List#replaceAll}.
905 >     *
906 >     * @param operator the operator to apply to each element
907 >     * @since TBD
908 >     */
909 >    /* public */ void replaceAll(UnaryOperator<E> operator) {
910 >        Objects.requireNonNull(operator);
911 >        final Object[] elements = this.elements;
912 >        final int capacity = elements.length;
913 >        int from, end, to, leftover;
914 >        leftover = (end = (from = head) + size)
915 >            - (to = (capacity - end >= 0) ? end : capacity);
916 >        for (;; from = 0, to = leftover, leftover = 0) {
917 >            for (int i = from; i < to; i++)
918 >                elements[i] = operator.apply(elementAt(i));
919 >            if (leftover == 0) break;
920          }
921 +        // checkInvariants();
922 +    }
923  
924 <        public void remove() {
925 <            if (lastRet < 0)
926 <                throw new IllegalStateException();
927 <            if (!delete(lastRet)) {
928 <                cursor = (cursor + 1) & (elements.length - 1);
929 <                fence = head;
924 >    /**
925 >     * @throws NullPointerException {@inheritDoc}
926 >     */
927 >    public boolean removeIf(Predicate<? super E> filter) {
928 >        Objects.requireNonNull(filter);
929 >        return bulkRemove(filter);
930 >    }
931 >
932 >    /**
933 >     * @throws NullPointerException {@inheritDoc}
934 >     */
935 >    public boolean removeAll(Collection<?> c) {
936 >        Objects.requireNonNull(c);
937 >        return bulkRemove(e -> c.contains(e));
938 >    }
939 >
940 >    /**
941 >     * @throws NullPointerException {@inheritDoc}
942 >     */
943 >    public boolean retainAll(Collection<?> c) {
944 >        Objects.requireNonNull(c);
945 >        return bulkRemove(e -> !c.contains(e));
946 >    }
947 >
948 >    /** Implementation of bulk remove methods. */
949 >    private boolean bulkRemove(Predicate<? super E> filter) {
950 >        // checkInvariants();
951 >        final Object[] elements = this.elements;
952 >        final int capacity = elements.length;
953 >        int i = head, j = i, remaining = size, deleted = 0;
954 >        try {
955 >            for (; remaining > 0; remaining--) {
956 >                @SuppressWarnings("unchecked") E e = (E) elements[i];
957 >                if (filter.test(e))
958 >                    deleted++;
959 >                else {
960 >                    if (j != i)
961 >                        elements[j] = e;
962 >                    if (++j >= capacity) j = 0;
963 >                }
964 >                if (++i >= capacity) i = 0;
965              }
966 <            lastRet = -1;
966 >            return deleted > 0;
967 >        } catch (Throwable ex) {
968 >            if (deleted > 0)
969 >                for (; remaining > 0; remaining--) {
970 >                    elements[j] = elements[i];
971 >                    if (++i >= capacity) i = 0;
972 >                    if (++j >= capacity) j = 0;
973 >                }
974 >            throw ex;
975 >        } finally {
976 >            size -= deleted;
977 >            clearSlice(elements, j, deleted);
978 >            // checkInvariants();
979          }
980      }
981  
# Line 671 | Line 989 | public class ArrayDeque<E> extends Abstr
989       */
990      public boolean contains(Object o) {
991          if (o != null) {
992 <            int mask = elements.length - 1;
993 <            int i = head;
994 <            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
995 <                if (o.equals(x))
996 <                    return true;
992 >            final Object[] elements = this.elements;
993 >            final int capacity = elements.length;
994 >            int from, end, to, leftover;
995 >            leftover = (end = (from = head) + size)
996 >                - (to = (capacity - end >= 0) ? end : capacity);
997 >            for (;; from = 0, to = leftover, leftover = 0) {
998 >                for (int i = from; i < to; i++)
999 >                    if (o.equals(elements[i]))
1000 >                        return true;
1001 >                if (leftover == 0) break;
1002              }
1003          }
1004          return false;
# Line 703 | Line 1026 | public class ArrayDeque<E> extends Abstr
1026       * The deque will be empty after this call returns.
1027       */
1028      public void clear() {
1029 <        int h = head;
1030 <        int t = tail;
1031 <        if (h != t) { // clear all cells
1032 <            head = tail = 0;
1033 <            int i = h;
1034 <            int mask = elements.length - 1;
1035 <            do {
1036 <                elements[i] = null;
1037 <                i = (i + 1) & mask;
1038 <            } while (i != t);
1039 <        }
1029 >        clearSlice(elements, head, size);
1030 >        size = head = 0;
1031 >        // checkInvariants();
1032 >    }
1033 >
1034 >    /**
1035 >     * Nulls out size elements, starting at head.
1036 >     */
1037 >    private static void clearSlice(Object[] elements, int head, int size) {
1038 >        final int capacity = elements.length, end = head + size;
1039 >        final int leg = (capacity - end >= 0) ? end : capacity;
1040 >        Arrays.fill(elements, head, leg, null);
1041 >        if (leg != end)
1042 >            Arrays.fill(elements, 0, end - capacity, null);
1043      }
1044  
1045      /**
# Line 730 | Line 1056 | public class ArrayDeque<E> extends Abstr
1056       * @return an array containing all of the elements in this deque
1057       */
1058      public Object[] toArray() {
1059 <        final int head = this.head;
1060 <        final int tail = this.tail;
1061 <        boolean wrap = (tail < head);
1062 <        int end = wrap ? tail + elements.length : tail;
1063 <        Object[] a = Arrays.copyOfRange(elements, head, end);
1064 <        if (wrap)
1065 <            System.arraycopy(elements, 0, a, elements.length - head, tail);
1059 >        return toArray(Object[].class);
1060 >    }
1061 >
1062 >    private <T> T[] toArray(Class<T[]> klazz) {
1063 >        final Object[] elements = this.elements;
1064 >        final int capacity = elements.length;
1065 >        final int head = this.head, end = head + size;
1066 >        final T[] a;
1067 >        if (end >= 0) {
1068 >            a = Arrays.copyOfRange(elements, head, end, klazz);
1069 >        } else {
1070 >            // integer overflow!
1071 >            a = Arrays.copyOfRange(elements, 0, size, klazz);
1072 >            System.arraycopy(elements, head, a, 0, capacity - head);
1073 >        }
1074 >        if (end - capacity > 0)
1075 >            System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1076          return a;
1077      }
1078  
# Line 778 | Line 1114 | public class ArrayDeque<E> extends Abstr
1114       */
1115      @SuppressWarnings("unchecked")
1116      public <T> T[] toArray(T[] a) {
1117 <        final int head = this.head;
1118 <        final int tail = this.tail;
1119 <        boolean wrap = (tail < head);
1120 <        int size = (tail - head) + (wrap ? elements.length : 0);
1121 <        int firstLeg = size - (wrap ? tail : 0);
1122 <        int len = a.length;
1123 <        if (size > len) {
1124 <            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
1125 <                                         a.getClass());
1126 <        } else {
1127 <            System.arraycopy(elements, head, a, 0, firstLeg);
1128 <            if (size < len)
793 <                a[size] = null;
794 <        }
795 <        if (wrap)
796 <            System.arraycopy(elements, 0, a, firstLeg, tail);
1117 >        final int size = this.size;
1118 >        if (size > a.length)
1119 >            return toArray((Class<T[]>) a.getClass());
1120 >        final Object[] elements = this.elements;
1121 >        final int capacity = elements.length;
1122 >        final int head = this.head, end = head + size;
1123 >        final int front = (capacity - end >= 0) ? size : capacity - head;
1124 >        System.arraycopy(elements, head, a, 0, front);
1125 >        if (front != size)
1126 >            System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1127 >        if (size < a.length)
1128 >            a[size] = null;
1129          return a;
1130      }
1131  
# Line 831 | Line 1163 | public class ArrayDeque<E> extends Abstr
1163          s.defaultWriteObject();
1164  
1165          // Write out size
1166 <        s.writeInt(size());
1166 >        s.writeInt(size);
1167  
1168          // Write out elements in order.
1169 <        int mask = elements.length - 1;
1170 <        for (int i = head; i != tail; i = (i + 1) & mask)
1171 <            s.writeObject(elements[i]);
1169 >        final Object[] elements = this.elements;
1170 >        final int capacity = elements.length;
1171 >        int from, end, to, leftover;
1172 >        leftover = (end = (from = head) + size)
1173 >            - (to = (capacity - end >= 0) ? end : capacity);
1174 >        for (;; from = 0, to = leftover, leftover = 0) {
1175 >            for (int i = from; i < to; i++)
1176 >                s.writeObject(elements[i]);
1177 >            if (leftover == 0) break;
1178 >        }
1179      }
1180  
1181      /**
# Line 851 | Line 1190 | public class ArrayDeque<E> extends Abstr
1190          s.defaultReadObject();
1191  
1192          // Read in size and allocate array
1193 <        int size = s.readInt();
855 <        allocateElements(size);
856 <        head = 0;
857 <        tail = size;
1193 >        elements = new Object[size = s.readInt()];
1194  
1195          // Read in all elements in the proper order.
1196          for (int i = 0; i < size; i++)
1197              elements[i] = s.readObject();
1198      }
1199  
1200 <    /**
1201 <     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1202 <     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1203 <     * deque.
1204 <     *
1205 <     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1206 <     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
1207 <     * {@link Spliterator#NONNULL}.  Overriding implementations should document
1208 <     * the reporting of additional characteristic values.
1209 <     *
1210 <     * @return a {@code Spliterator} over the elements in this deque
1211 <     * @since 1.8
1212 <     */
1213 <    public Spliterator<E> spliterator() {
1214 <        return new DeqSpliterator<>(this, -1, -1);
1215 <    }
1216 <
881 <    static final class DeqSpliterator<E> implements Spliterator<E> {
882 <        private final ArrayDeque<E> deq;
883 <        private int fence;  // -1 until first use
884 <        private int index;  // current index, modified on traverse/split
885 <
886 <        /** Creates new spliterator covering the given array and range. */
887 <        DeqSpliterator(ArrayDeque<E> deq, int origin, int 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 t = getFence(), h = index, n = deq.elements.length;
904 <            if (h != t && ((h + 1) & (n - 1)) != t) {
905 <                if (h > t)
906 <                    t += n;
907 <                int m = ((h + t) >>> 1) & (n - 1);
908 <                return new DeqSpliterator<E>(deq, h, index = m);
909 <            }
910 <            return null;
911 <        }
912 <
913 <        public void forEachRemaining(Consumer<? super E> consumer) {
914 <            if (consumer == null)
915 <                throw new NullPointerException();
916 <            Object[] a = deq.elements;
917 <            int m = a.length - 1, f = getFence(), i = index;
918 <            index = f;
919 <            while (i != f) {
920 <                @SuppressWarnings("unchecked") E e = (E)a[i];
921 <                i = (i + 1) & m;
922 <                if (e == null)
923 <                    throw new ConcurrentModificationException();
924 <                consumer.accept(e);
925 <            }
926 <        }
927 <
928 <        public boolean tryAdvance(Consumer<? super E> consumer) {
929 <            if (consumer == null)
930 <                throw new NullPointerException();
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 <                consumer.accept(e);
939 <                return true;
940 <            }
941 <            return false;
942 <        }
943 <
944 <        public long estimateSize() {
945 <            int n = getFence() - index;
946 <            if (n < 0)
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;
1200 >    /** debugging */
1201 >    void checkInvariants() {
1202 >        try {
1203 >            int capacity = elements.length;
1204 >            // assert size >= 0 && size <= capacity;
1205 >            // assert head >= 0;
1206 >            // assert capacity == 0 || head < capacity;
1207 >            // assert size == 0 || elements[head] != null;
1208 >            // assert size == 0 || elements[tail()] != null;
1209 >            // assert size == capacity || elements[dec(head, capacity)] == null;
1210 >            // assert size == capacity || elements[inc(tail(), capacity)] == null;
1211 >        } catch (Throwable t) {
1212 >            System.err.printf("head=%d size=%d capacity=%d%n",
1213 >                              head, size, elements.length);
1214 >            System.err.printf("elements=%s%n",
1215 >                              Arrays.toString(elements));
1216 >            throw t;
1217          }
1218      }
1219  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines