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.40 by jsr166, Sun Feb 26 22:43:03 2012 UTC vs.
Revision 1.95 by jsr166, Sat Oct 29 19:10:27 2016 UTC

# Line 5 | Line 5
5  
6   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
15   * deques have no capacity restrictions; they grow as necessary to support
# Line 49 | Line 54 | package java.util;
54   * Java Collections Framework</a>.
55   *
56   * @author  Josh Bloch and Doug Lea
57 + * @param <E> the type of elements held in this deque
58   * @since   1.6
53 * @param <E> the type of elements held in this collection
59   */
60   public class ArrayDeque<E> extends AbstractCollection<E>
61 <                           implements Deque<E>, Cloneable, java.io.Serializable
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
62 <     * full, except transiently within an addX method where it is
63 <     * resized (see doubleCapacity) immediately upon becoming full,
64 <     * thus avoiding head and tail wrapping around to equal each
65 <     * other.  We also guarantee that all array cells not holding
66 <     * deque elements are always null.
65 >     * We guarantee that all array cells not holding deque elements
66 >     * are always null.
67       */
68 <    private transient Object[] elements;
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.
74 <     */
75 <    private transient int head;
76 <
77 <    /**
78 <     * The index at which the next element would be added to the tail
79 <     * of the deque (via addLast(E), add(E), or push(E)).
80 <     */
81 <    private transient int tail;
82 <
83 <    /**
84 <     * The minimum capacity that we'll use for a newly created deque.
85 <     * Must be a power of 2.
73 >     * arbitrary number 0 <= head < elements.length if the deque is empty.
74       */
75 <    private static final int MIN_INITIAL_CAPACITY = 8;
75 >    transient int head;
76  
77 <    // ******  Array allocation and resizing utilities ******
77 >    /** Number of elements in this collection. */
78 >    transient int size;
79  
80      /**
81 <     * Allocates empty array to hold the given number of elements.
82 <     *
83 <     * @param numElements  the number of elements to hold
84 <     */
85 <    private void allocateElements(int numElements) {
86 <        int initialCapacity = MIN_INITIAL_CAPACITY;
87 <        // Find the best power of two to hold elements.
88 <        // Tests "<=" because arrays aren't kept full.
89 <        if (numElements >= initialCapacity) {
90 <            initialCapacity = numElements;
91 <            initialCapacity |= (initialCapacity >>>  1);
92 <            initialCapacity |= (initialCapacity >>>  2);
93 <            initialCapacity |= (initialCapacity >>>  4);
94 <            initialCapacity |= (initialCapacity >>>  8);
95 <            initialCapacity |= (initialCapacity >>> 16);
96 <            initialCapacity++;
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 >    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
87 >
88 >    /**
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 void 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 >        // checkInvariants();
114 >    }
115  
116 <            if (initialCapacity < 0)   // Too many elements, must back off
117 <                initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
116 >    /** Capacity calculation for edge conditions, especially overflow. */
117 >    private int newCapacity(int needed, int jump) {
118 >        final int oldCapacity = elements.length, minCapacity;
119 >        if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
120 >            if (minCapacity < 0)
121 >                throw new IllegalStateException("Sorry, deque too big");
122 >            return Integer.MAX_VALUE;
123          }
124 <        elements = new Object[initialCapacity];
124 >        if (needed > jump)
125 >            return minCapacity;
126 >        return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
127 >            ? oldCapacity + jump
128 >            : MAX_ARRAY_SIZE;
129      }
130  
131      /**
132 <     * Doubles the capacity of this deque.  Call only when full, i.e.,
133 <     * when head and tail have wrapped around to become equal.
132 >     * Increases the internal storage of this collection, if necessary,
133 >     * to ensure that it can hold at least the given number of elements.
134 >     *
135 >     * @param minCapacity the desired minimum capacity
136 >     * @since TBD
137       */
138 <    private void doubleCapacity() {
139 <        assert head == tail;
140 <        int p = head;
141 <        int n = elements.length;
123 <        int r = n - p; // number of elements to the right of p
124 <        int newCapacity = n << 1;
125 <        if (newCapacity < 0)
126 <            throw new IllegalStateException("Sorry, deque too big");
127 <        Object[] a = new Object[newCapacity];
128 <        System.arraycopy(elements, p, a, 0, r);
129 <        System.arraycopy(elements, 0, a, r, p);
130 <        elements = a;
131 <        head = 0;
132 <        tail = n;
138 >    /* public */ void ensureCapacity(int minCapacity) {
139 >        if (minCapacity > elements.length)
140 >            grow(minCapacity - elements.length);
141 >        // checkInvariants();
142      }
143  
144      /**
145 <     * Copies the elements from our element array into the specified array,
137 <     * in order (from first to last element in the deque).  It is assumed
138 <     * that the array is large enough to hold all elements in the deque.
145 >     * Minimizes the internal storage of this collection.
146       *
147 <     * @return its argument
147 >     * @since TBD
148       */
149 <    private <T> T[] copyElements(T[] a) {
150 <        if (head < tail) {
151 <            System.arraycopy(elements, head, a, 0, size());
152 <        } else if (head > tail) {
146 <            int headPortionLen = elements.length - head;
147 <            System.arraycopy(elements, head, a, 0, headPortionLen);
148 <            System.arraycopy(elements, 0, a, headPortionLen, tail);
149 >    /* public */ void trimToSize() {
150 >        if (size < elements.length) {
151 >            elements = toArray();
152 >            head = 0;
153          }
154 <        return a;
154 >        // checkInvariants();
155      }
156  
157      /**
# Line 162 | Line 166 | public class ArrayDeque<E> extends Abstr
166       * Constructs an empty array deque with an initial capacity
167       * sufficient to hold the specified number of elements.
168       *
169 <     * @param numElements  lower bound on initial capacity of the deque
169 >     * @param numElements lower bound on initial capacity of the deque
170       */
171      public ArrayDeque(int numElements) {
172 <        allocateElements(numElements);
172 >        elements = new Object[numElements];
173      }
174  
175      /**
# Line 179 | Line 183 | public class ArrayDeque<E> extends Abstr
183       * @throws NullPointerException if the specified collection is null
184       */
185      public ArrayDeque(Collection<? extends E> c) {
186 <        allocateElements(c.size());
187 <        addAll(c);
186 >        Object[] es = c.toArray();
187 >        // defend against c.toArray (incorrectly) not returning Object[]
188 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
189 >        if (es.getClass() != Object[].class)
190 >            es = Arrays.copyOf(es, es.length, Object[].class);
191 >        for (Object obj : es)
192 >            Objects.requireNonNull(obj);
193 >        this.elements = es;
194 >        this.size = es.length;
195 >    }
196 >
197 >    /**
198 >     * Increments i, mod modulus.
199 >     * Precondition and postcondition: 0 <= i < modulus.
200 >     */
201 >    static final int inc(int i, int modulus) {
202 >        if (++i >= modulus) i = 0;
203 >        return i;
204 >    }
205 >
206 >    /**
207 >     * Decrements i, mod modulus.
208 >     * Precondition and postcondition: 0 <= i < modulus.
209 >     */
210 >    static final int dec(int i, int modulus) {
211 >        if (--i < 0) i = modulus - 1;
212 >        return i;
213 >    }
214 >
215 >    /**
216 >     * Adds i and j, mod modulus.
217 >     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
218 >     */
219 >    static final int add(int i, int j, int modulus) {
220 >        if ((i += j) - modulus >= 0) i -= modulus;
221 >        return i;
222 >    }
223 >
224 >    /**
225 >     * Returns the array index of the last element.
226 >     * May return invalid index -1 if there are no elements.
227 >     */
228 >    final int tail() {
229 >        return add(head, size - 1, elements.length);
230 >    }
231 >
232 >    /**
233 >     * Returns element at array index i.
234 >     */
235 >    @SuppressWarnings("unchecked")
236 >    private E elementAt(int i) {
237 >        return (E) elements[i];
238 >    }
239 >
240 >    /**
241 >     * A version of elementAt that checks for null elements.
242 >     * This check doesn't catch all possible comodifications,
243 >     * but does catch ones that corrupt traversal.  It's a little
244 >     * surprising that javac allows this abuse of generics.
245 >     */
246 >    static final <E> E nonNullElementAt(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 194 | 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[] es;
267 >        int capacity, h;
268 >        final int s;
269 >        if ((s = size) == (capacity = (es = elements).length)) {
270 >            grow(1);
271 >            capacity = (es = elements).length;
272 >        }
273 >        if ((h = head - 1) < 0) h = capacity - 1;
274 >        es[head = h] = e;
275 >        size = s + 1;
276 >        // checkInvariants();
277      }
278  
279      /**
# Line 210 | 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[] es;
291 >        int capacity;
292 >        final int s;
293 >        if ((s = size) == (capacity = (es = elements).length)) {
294 >            grow(1);
295 >            capacity = (es = elements).length;
296 >        }
297 >        es[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 245 | 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 <        int h = head;
370 <        @SuppressWarnings("unchecked")
371 <        E result = (E) elements[h];
268 <        // Element is null if deque empty
269 <        if (result == null)
369 >        // checkInvariants();
370 >        int s, h;
371 >        if ((s = size) <= 0)
372              return null;
373 <        elements[h] = null;     // Must null out slot
374 <        head = (h + 1) & (elements.length - 1);
375 <        return result;
373 >        final Object[] elements = this.elements;
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 <        int t = (tail - 1) & (elements.length - 1);
384 <        @SuppressWarnings("unchecked")
385 <        E result = (E) elements[t];
280 <        if (result == null)
383 >        // checkInvariants();
384 >        final int s, tail;
385 >        if ((s = size) <= 0)
386              return null;
387 <        elements[t] = null;
388 <        tail = t;
389 <        return result;
387 >        final Object[] elements = this.elements;
388 >        @SuppressWarnings("unchecked")
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)
294 <            throw new NoSuchElementException();
295 <        return result;
399 >        // checkInvariants();
400 >        if (size <= 0) throw new NoSuchElementException();
401 >        return elementAt(head);
402      }
403  
404      /**
405       * @throws NoSuchElementException {@inheritDoc}
406       */
407 +    @SuppressWarnings("unchecked")
408      public E getLast() {
409 <        @SuppressWarnings("unchecked")
410 <        E result = (E) elements[(tail - 1) & (elements.length - 1)];
411 <        if (result == null)
412 <            throw new NoSuchElementException();
413 <        return result;
409 >        // checkInvariants();
410 >        final int s;
411 >        if ((s = size) <= 0) throw new NoSuchElementException();
412 >        final Object[] elements = this.elements;
413 >        return (E) elements[add(head, s - 1, elements.length)];
414      }
415  
309    @SuppressWarnings("unchecked")
416      public E peekFirst() {
417 <        // elements[head] is null if deque empty
418 <        return (E) elements[head];
417 >        // checkInvariants();
418 >        return (size <= 0) ? null : elementAt(head);
419      }
420  
421      @SuppressWarnings("unchecked")
422      public E peekLast() {
423 <        return (E) elements[(tail - 1) & (elements.length - 1)];
423 >        // checkInvariants();
424 >        final int s;
425 >        if ((s = size) <= 0) return null;
426 >        final Object[] elements = this.elements;
427 >        return (E) elements[add(head, s - 1, elements.length)];
428      }
429  
430      /**
# Line 330 | Line 440 | public class ArrayDeque<E> extends Abstr
440       * @return {@code true} if the deque contained the specified element
441       */
442      public boolean removeFirstOccurrence(Object o) {
443 <        if (o == null)
444 <            return false;
445 <        int mask = elements.length - 1;
446 <        int i = head;
447 <        Object x;
448 <        while ( (x = elements[i]) != null) {
449 <            if (o.equals(x)) {
450 <                delete(i);
451 <                return true;
443 >        if (o != null) {
444 >            final Object[] elements = this.elements;
445 >            final int capacity = elements.length;
446 >            int i, end, to, todo;
447 >            todo = (end = (i = head) + size)
448 >                - (to = (capacity - end >= 0) ? end : capacity);
449 >            for (;; to = todo, i = 0, todo = 0) {
450 >                for (; i < to; i++)
451 >                    if (o.equals(elements[i])) {
452 >                        delete(i);
453 >                        return true;
454 >                    }
455 >                if (todo == 0) break;
456              }
343            i = (i + 1) & mask;
457          }
458          return false;
459      }
# Line 358 | Line 471 | public class ArrayDeque<E> extends Abstr
471       * @return {@code true} if the deque contained the specified element
472       */
473      public boolean removeLastOccurrence(Object o) {
474 <        if (o == null)
475 <            return false;
476 <        int mask = elements.length - 1;
477 <        int i = (tail - 1) & mask;
478 <        Object x;
479 <        while ( (x = elements[i]) != null) {
480 <            if (o.equals(x)) {
481 <                delete(i);
482 <                return true;
474 >        if (o != null) {
475 >            final Object[] elements = this.elements;
476 >            final int capacity = elements.length;
477 >            int i, to, end, todo;
478 >            todo = (to = ((end = (i = tail()) - size) >= -1) ? end : -1) - end;
479 >            for (;; to = (i = capacity - 1) - todo, todo = 0) {
480 >                for (; i > to; i--)
481 >                    if (o.equals(elements[i])) {
482 >                        delete(i);
483 >                        return true;
484 >                    }
485 >                if (todo == 0) break;
486              }
371            i = (i - 1) & mask;
487          }
488          return false;
489      }
# Line 487 | Line 602 | public class ArrayDeque<E> extends Abstr
602          return removeFirst();
603      }
604  
490    private void checkInvariants() {
491        assert elements[tail] == null;
492        assert head == tail ? elements[head] == null :
493            (elements[head] != null &&
494             elements[(tail - 1) & (elements.length - 1)] != null);
495        assert elements[(head - 1) & (elements.length - 1)] == null;
496    }
497
605      /**
606 <     * Removes the element at the specified position in the elements array,
607 <     * adjusting head and tail as necessary.  This can result in motion of
608 <     * elements backwards or forwards in the array.
606 >     * Removes the element at the specified position in the elements array.
607 >     * This can result in forward or backwards motion of array elements.
608 >     * We optimize for least element motion.
609       *
610       * <p>This method is called delete rather than remove to emphasize
611       * that its semantics differ from those of {@link List#remove(int)}.
612       *
613       * @return true if elements moved backwards
614       */
615 <    private boolean delete(int i) {
616 <        checkInvariants();
615 >    boolean delete(int i) {
616 >        // checkInvariants();
617          final Object[] elements = this.elements;
618 <        final int mask = elements.length - 1;
618 >        final int capacity = elements.length;
619          final int h = head;
620 <        final int t = tail;
621 <        final int front = (i - h) & mask;
622 <        final int back  = (t - i) & mask;
516 <
517 <        // Invariant: head <= i < tail mod circularity
518 <        if (front >= ((t - h) & mask))
519 <            throw new ConcurrentModificationException();
520 <
521 <        // Optimize for least element motion
620 >        int front;              // number of elements before to-be-deleted elt
621 >        if ((front = i - h) < 0) front += capacity;
622 >        final int back = size - front - 1; // number of elements after
623          if (front < back) {
624 +            // move front elements forwards
625              if (h <= i) {
626                  System.arraycopy(elements, h, elements, h + 1, front);
627              } else { // Wrap around
628                  System.arraycopy(elements, 0, elements, 1, i);
629 <                elements[0] = elements[mask];
630 <                System.arraycopy(elements, h, elements, h + 1, mask - h);
629 >                elements[0] = elements[capacity - 1];
630 >                System.arraycopy(elements, h, elements, h + 1, front - (i + 1));
631              }
632              elements[h] = null;
633 <            head = (h + 1) & mask;
633 >            if ((head = (h + 1)) >= capacity) head = 0;
634 >            size--;
635 >            // checkInvariants();
636              return false;
637          } else {
638 <            if (i < t) { // Copy the null tail as well
638 >            // move back elements backwards
639 >            int tail = tail();
640 >            if (i <= tail) {
641                  System.arraycopy(elements, i + 1, elements, i, back);
536                tail = t - 1;
642              } else { // Wrap around
643 <                System.arraycopy(elements, i + 1, elements, i, mask - i);
644 <                elements[mask] = elements[0];
645 <                System.arraycopy(elements, 1, elements, 0, t);
646 <                tail = (t - 1) & mask;
643 >                int firstLeg = capacity - (i + 1);
644 >                System.arraycopy(elements, i + 1, elements, i, firstLeg);
645 >                elements[capacity - 1] = elements[0];
646 >                System.arraycopy(elements, 1, elements, 0, back - firstLeg - 1);
647              }
648 +            elements[tail] = null;
649 +            size--;
650 +            // checkInvariants();
651              return true;
652          }
653      }
# Line 552 | Line 660 | public class ArrayDeque<E> extends Abstr
660       * @return the number of elements in this deque
661       */
662      public int size() {
663 <        return (tail - head) & (elements.length - 1);
663 >        return size;
664      }
665  
666      /**
# Line 561 | Line 669 | public class ArrayDeque<E> extends Abstr
669       * @return {@code true} if this deque contains no elements
670       */
671      public boolean isEmpty() {
672 <        return head == tail;
672 >        return size == 0;
673      }
674  
675      /**
# Line 581 | Line 689 | public class ArrayDeque<E> extends Abstr
689      }
690  
691      private class DeqIterator implements Iterator<E> {
692 <        /**
693 <         * Index of element to be returned by subsequent call to next.
586 <         */
587 <        private int cursor = head;
692 >        /** Index of element to be returned by subsequent call to next. */
693 >        int cursor;
694  
695 <        /**
696 <         * Tail recorded at construction (also in remove), to stop
591 <         * iterator and also to check for comodification.
592 <         */
593 <        private int fence = tail;
695 >        /** Number of elements yet to be returned. */
696 >        int remaining = size;
697  
698          /**
699           * Index of element returned by most recent call to next.
700           * Reset to -1 if element is deleted by a call to remove.
701           */
702 <        private int lastRet = -1;
702 >        int lastRet = -1;
703 >
704 >        DeqIterator() { cursor = head; }
705  
706 <        public boolean hasNext() {
707 <            return cursor != fence;
706 >        public final boolean hasNext() {
707 >            return remaining > 0;
708          }
709  
710          public E next() {
711 <            if (cursor == fence)
711 >            if (remaining <= 0)
712                  throw new NoSuchElementException();
713 <            @SuppressWarnings("unchecked")
714 <            E result = (E) elements[cursor];
610 <            // This check doesn't catch all possible comodifications,
611 <            // but does catch the ones that corrupt traversal
612 <            if (tail != fence || result == null)
613 <                throw new ConcurrentModificationException();
713 >            final Object[] elements = ArrayDeque.this.elements;
714 >            E e = nonNullElementAt(elements, cursor);
715              lastRet = cursor;
716 <            cursor = (cursor + 1) & (elements.length - 1);
717 <            return result;
716 >            if (++cursor >= elements.length) cursor = 0;
717 >            remaining--;
718 >            return e;
719          }
720  
721 <        public void remove() {
721 >        void postDelete(boolean leftShifted) {
722 >            if (leftShifted)
723 >                if (--cursor < 0) cursor = elements.length - 1;
724 >        }
725 >
726 >        public final void remove() {
727              if (lastRet < 0)
728                  throw new IllegalStateException();
729 <            if (delete(lastRet)) { // if left-shifted, undo increment in next()
623 <                cursor = (cursor - 1) & (elements.length - 1);
624 <                fence = tail;
625 <            }
729 >            postDelete(delete(lastRet));
730              lastRet = -1;
731          }
628    }
629
630    private class DescendingIterator implements Iterator<E> {
631        /*
632         * This class is nearly a mirror-image of DeqIterator, using
633         * tail instead of head for initial cursor, and head instead of
634         * tail for fence.
635         */
636        private int cursor = tail;
637        private int fence = head;
638        private int lastRet = -1;
732  
733 <        public boolean hasNext() {
734 <            return cursor != fence;
733 >        public void forEachRemaining(Consumer<? super E> action) {
734 >            final int k;
735 >            if ((k = remaining) > 0) {
736 >                remaining = 0;
737 >                ArrayDeque.forEachRemaining(action, elements, cursor, k);
738 >                if ((lastRet = cursor + k - 1) >= elements.length)
739 >                    lastRet -= elements.length;
740 >            }
741          }
742 +    }
743  
744 <        public E next() {
745 <            if (cursor == fence)
744 >    private class DescendingIterator extends DeqIterator {
745 >        DescendingIterator() { cursor = tail(); }
746 >
747 >        public final E next() {
748 >            if (remaining <= 0)
749                  throw new NoSuchElementException();
750 <            cursor = (cursor - 1) & (elements.length - 1);
751 <            @SuppressWarnings("unchecked")
649 <            E result = (E) elements[cursor];
650 <            if (head != fence || result == null)
651 <                throw new ConcurrentModificationException();
750 >            final Object[] elements = ArrayDeque.this.elements;
751 >            E e = nonNullElementAt(elements, cursor);
752              lastRet = cursor;
753 <            return result;
753 >            if (--cursor < 0) cursor = elements.length - 1;
754 >            remaining--;
755 >            return e;
756          }
757  
758 <        public void remove() {
759 <            if (lastRet < 0)
760 <                throw new IllegalStateException();
761 <            if (!delete(lastRet)) {
762 <                cursor = (cursor + 1) & (elements.length - 1);
763 <                fence = head;
758 >        void postDelete(boolean leftShifted) {
759 >            if (!leftShifted)
760 >                if (++cursor >= elements.length) cursor = 0;
761 >        }
762 >
763 >        public final void forEachRemaining(Consumer<? super E> action) {
764 >            final int k;
765 >            if ((k = remaining) > 0) {
766 >                remaining = 0;
767 >                forEachRemainingDescending(action, elements, cursor, k);
768 >                if ((lastRet = cursor - (k - 1)) < 0)
769 >                    lastRet += elements.length;
770              }
771 <            lastRet = -1;
771 >        }
772 >    }
773 >
774 >    /**
775 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
776 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
777 >     * deque.
778 >     *
779 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
780 >     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
781 >     * {@link Spliterator#NONNULL}.  Overriding implementations should document
782 >     * the reporting of additional characteristic values.
783 >     *
784 >     * @return a {@code Spliterator} over the elements in this deque
785 >     * @since 1.8
786 >     */
787 >    public Spliterator<E> spliterator() {
788 >        return new ArrayDequeSpliterator();
789 >    }
790 >
791 >    final class ArrayDequeSpliterator implements Spliterator<E> {
792 >        private int cursor;
793 >        private int remaining; // -1 until late-binding first use
794 >
795 >        /** Constructs late-binding spliterator over all elements. */
796 >        ArrayDequeSpliterator() {
797 >            this.remaining = -1;
798 >        }
799 >
800 >        /** Constructs spliterator over the given slice. */
801 >        ArrayDequeSpliterator(int cursor, int count) {
802 >            this.cursor = cursor;
803 >            this.remaining = count;
804 >        }
805 >
806 >        /** Ensures late-binding initialization; then returns remaining. */
807 >        private int remaining() {
808 >            if (remaining < 0) {
809 >                cursor = head;
810 >                remaining = size;
811 >            }
812 >            return remaining;
813 >        }
814 >
815 >        public ArrayDequeSpliterator trySplit() {
816 >            final int mid;
817 >            if ((mid = remaining() >> 1) > 0) {
818 >                int oldCursor = cursor;
819 >                cursor = add(cursor, mid, elements.length);
820 >                remaining -= mid;
821 >                return new ArrayDequeSpliterator(oldCursor, mid);
822 >            }
823 >            return null;
824 >        }
825 >
826 >        public void forEachRemaining(Consumer<? super E> action) {
827 >            final int k = remaining(); // side effect!
828 >            remaining = 0;
829 >            ArrayDeque.forEachRemaining(action, elements, cursor, k);
830 >        }
831 >
832 >        public boolean tryAdvance(Consumer<? super E> action) {
833 >            Objects.requireNonNull(action);
834 >            final int k;
835 >            if ((k = remaining()) <= 0)
836 >                return false;
837 >            action.accept(nonNullElementAt(elements, cursor));
838 >            if (++cursor >= elements.length) cursor = 0;
839 >            remaining = k - 1;
840 >            return true;
841 >        }
842 >
843 >        public long estimateSize() {
844 >            return remaining();
845 >        }
846 >
847 >        public int characteristics() {
848 >            return Spliterator.NONNULL
849 >                | Spliterator.ORDERED
850 >                | Spliterator.SIZED
851 >                | Spliterator.SUBSIZED;
852 >        }
853 >    }
854 >
855 >    @SuppressWarnings("unchecked")
856 >    public void forEach(Consumer<? super E> action) {
857 >        Objects.requireNonNull(action);
858 >        final Object[] elements = this.elements;
859 >        final int capacity = elements.length;
860 >        int i, end, to, todo;
861 >        todo = (end = (i = head) + size)
862 >            - (to = (capacity - end >= 0) ? end : capacity);
863 >        for (;; to = todo, i = 0, todo = 0) {
864 >            for (; i < to; i++)
865 >                action.accept((E) elements[i]);
866 >            if (todo == 0) break;
867 >        }
868 >        // checkInvariants();
869 >    }
870 >
871 >    /**
872 >     * Calls action on remaining elements, starting at index i and
873 >     * traversing in ascending order.  A variant of forEach that also
874 >     * checks for concurrent modification, for use in iterators.
875 >     */
876 >    static <E> void forEachRemaining(
877 >        Consumer<? super E> action, Object[] elements, int i, int remaining) {
878 >        Objects.requireNonNull(action);
879 >        final int capacity = elements.length;
880 >        int end, to, todo;
881 >        todo = (end = i + remaining)
882 >            - (to = (capacity - end >= 0) ? end : capacity);
883 >        for (;; to = todo, i = 0, todo = 0) {
884 >            for (; i < to; i++)
885 >                action.accept(nonNullElementAt(elements, i));
886 >            if (todo == 0) break;
887 >        }
888 >    }
889 >
890 >    static <E> void forEachRemainingDescending(
891 >        Consumer<? super E> action, Object[] elements, int i, int remaining) {
892 >        Objects.requireNonNull(action);
893 >        final int capacity = elements.length;
894 >        int end, to, todo;
895 >        todo = (to = ((end = i - remaining) >= -1) ? end : -1) - end;
896 >        for (;; to = (i = capacity - 1) - todo, todo = 0) {
897 >            for (; i > to; i--)
898 >                action.accept(nonNullElementAt(elements, i));
899 >            if (todo == 0) break;
900 >        }
901 >    }
902 >
903 >    /**
904 >     * Replaces each element of this deque with the result of applying the
905 >     * operator to that element, as specified by {@link List#replaceAll}.
906 >     *
907 >     * @param operator the operator to apply to each element
908 >     * @since TBD
909 >     */
910 >    /* public */ void replaceAll(UnaryOperator<E> operator) {
911 >        Objects.requireNonNull(operator);
912 >        final Object[] elements = this.elements;
913 >        final int capacity = elements.length;
914 >        int i, end, to, todo;
915 >        todo = (end = (i = head) + size)
916 >            - (to = (capacity - end >= 0) ? end : capacity);
917 >        for (;; to = todo, i = 0, todo = 0) {
918 >            for (; i < to; i++)
919 >                elements[i] = operator.apply(elementAt(i));
920 >            if (todo == 0) break;
921 >        }
922 >        // checkInvariants();
923 >    }
924 >
925 >    /**
926 >     * @throws NullPointerException {@inheritDoc}
927 >     */
928 >    public boolean removeIf(Predicate<? super E> filter) {
929 >        Objects.requireNonNull(filter);
930 >        return bulkRemove(filter);
931 >    }
932 >
933 >    /**
934 >     * @throws NullPointerException {@inheritDoc}
935 >     */
936 >    public boolean removeAll(Collection<?> c) {
937 >        Objects.requireNonNull(c);
938 >        return bulkRemove(e -> c.contains(e));
939 >    }
940 >
941 >    /**
942 >     * @throws NullPointerException {@inheritDoc}
943 >     */
944 >    public boolean retainAll(Collection<?> c) {
945 >        Objects.requireNonNull(c);
946 >        return bulkRemove(e -> !c.contains(e));
947 >    }
948 >
949 >    /** Implementation of bulk remove methods. */
950 >    private boolean bulkRemove(Predicate<? super E> filter) {
951 >        // checkInvariants();
952 >        final Object[] elements = this.elements;
953 >        final int capacity = elements.length;
954 >        int i = head, j = i, remaining = size, deleted = 0;
955 >        try {
956 >            for (; remaining > 0; remaining--) {
957 >                @SuppressWarnings("unchecked") E e = (E) elements[i];
958 >                if (filter.test(e))
959 >                    deleted++;
960 >                else {
961 >                    if (j != i)
962 >                        elements[j] = e;
963 >                    if (++j >= capacity) j = 0;
964 >                }
965 >                if (++i >= capacity) i = 0;
966 >            }
967 >            return deleted > 0;
968 >        } catch (Throwable ex) {
969 >            if (deleted > 0)
970 >                for (; remaining > 0; remaining--) {
971 >                    elements[j] = elements[i];
972 >                    if (++i >= capacity) i = 0;
973 >                    if (++j >= capacity) j = 0;
974 >                }
975 >            throw ex;
976 >        } finally {
977 >            size -= deleted;
978 >            clearSlice(elements, j, deleted);
979 >            // checkInvariants();
980          }
981      }
982  
# Line 673 | Line 989 | public class ArrayDeque<E> extends Abstr
989       * @return {@code true} if this deque contains the specified element
990       */
991      public boolean contains(Object o) {
992 <        if (o == null)
993 <            return false;
994 <        int mask = elements.length - 1;
995 <        int i = head;
996 <        Object x;
997 <        while ( (x = elements[i]) != null) {
998 <            if (o.equals(x))
999 <                return true;
1000 <            i = (i + 1) & mask;
992 >        if (o != null) {
993 >            final Object[] elements = this.elements;
994 >            final int capacity = elements.length;
995 >            int i, end, to, todo;
996 >            todo = (end = (i = head) + size)
997 >                - (to = (capacity - end >= 0) ? end : capacity);
998 >            for (;; to = todo, i = 0, todo = 0) {
999 >                for (; i < to; i++)
1000 >                    if (o.equals(elements[i]))
1001 >                        return true;
1002 >                if (todo == 0) break;
1003 >            }
1004          }
1005          return false;
1006      }
# Line 694 | Line 1013 | public class ArrayDeque<E> extends Abstr
1013       * Returns {@code true} if this deque contained the specified element
1014       * (or equivalently, if this deque changed as a result of the call).
1015       *
1016 <     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
1016 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1017       *
1018       * @param o element to be removed from this deque, if present
1019       * @return {@code true} if this deque contained the specified element
# Line 708 | Line 1027 | public class ArrayDeque<E> extends Abstr
1027       * The deque will be empty after this call returns.
1028       */
1029      public void clear() {
1030 <        int h = head;
1031 <        int t = tail;
1032 <        if (h != t) { // clear all cells
1033 <            head = tail = 0;
1034 <            int i = h;
1035 <            int mask = elements.length - 1;
1036 <            do {
1037 <                elements[i] = null;
1038 <                i = (i + 1) & mask;
1039 <            } while (i != t);
1040 <        }
1030 >        clearSlice(elements, head, size);
1031 >        size = head = 0;
1032 >        // checkInvariants();
1033 >    }
1034 >
1035 >    /**
1036 >     * Nulls out count elements, starting at array index from.
1037 >     */
1038 >    private static void clearSlice(Object[] elements, int from, int count) {
1039 >        final int capacity = elements.length, end = from + count;
1040 >        final int leg = (capacity - end >= 0) ? end : capacity;
1041 >        Arrays.fill(elements, from, leg, null);
1042 >        if (leg != end)
1043 >            Arrays.fill(elements, 0, end - capacity, null);
1044      }
1045  
1046      /**
# Line 735 | Line 1057 | public class ArrayDeque<E> extends Abstr
1057       * @return an array containing all of the elements in this deque
1058       */
1059      public Object[] toArray() {
1060 <        return copyElements(new Object[size()]);
1060 >        return toArray(Object[].class);
1061 >    }
1062 >
1063 >    private <T> T[] toArray(Class<T[]> klazz) {
1064 >        final Object[] elements = this.elements;
1065 >        final int capacity = elements.length;
1066 >        final int head = this.head, end = head + size;
1067 >        final T[] a;
1068 >        if (end >= 0) {
1069 >            a = Arrays.copyOfRange(elements, head, end, klazz);
1070 >        } else {
1071 >            // integer overflow!
1072 >            a = Arrays.copyOfRange(elements, 0, size, klazz);
1073 >            System.arraycopy(elements, head, a, 0, capacity - head);
1074 >        }
1075 >        if (end - capacity > 0)
1076 >            System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1077 >        return a;
1078      }
1079  
1080      /**
# Line 760 | Line 1099 | public class ArrayDeque<E> extends Abstr
1099       * The following code can be used to dump the deque into a newly
1100       * allocated array of {@code String}:
1101       *
1102 <     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1102 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1103       *
1104       * Note that {@code toArray(new Object[0])} is identical in function to
1105       * {@code toArray()}.
# Line 776 | Line 1115 | public class ArrayDeque<E> extends Abstr
1115       */
1116      @SuppressWarnings("unchecked")
1117      public <T> T[] toArray(T[] a) {
1118 <        int size = size();
1119 <        if (a.length < size)
1120 <            a = (T[])java.lang.reflect.Array.newInstance(
1121 <                    a.getClass().getComponentType(), size);
1122 <        copyElements(a);
1123 <        if (a.length > size)
1118 >        final int size = this.size;
1119 >        if (size > a.length)
1120 >            return toArray((Class<T[]>) a.getClass());
1121 >        final Object[] elements = this.elements;
1122 >        final int capacity = elements.length;
1123 >        final int head = this.head, end = head + size;
1124 >        final int front = (capacity - end >= 0) ? size : capacity - head;
1125 >        System.arraycopy(elements, head, a, 0, front);
1126 >        if (front != size)
1127 >            System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1128 >        if (size < a.length)
1129              a[size] = null;
1130          return a;
1131      }
# Line 809 | Line 1153 | public class ArrayDeque<E> extends Abstr
1153      /**
1154       * Saves this deque to a stream (that is, serializes it).
1155       *
1156 +     * @param s the stream
1157 +     * @throws java.io.IOException if an I/O error occurs
1158       * @serialData The current size ({@code int}) of the deque,
1159       * followed by all of its elements (each an object reference) in
1160       * first-to-last order.
# Line 818 | Line 1164 | public class ArrayDeque<E> extends Abstr
1164          s.defaultWriteObject();
1165  
1166          // Write out size
1167 <        s.writeInt(size());
1167 >        s.writeInt(size);
1168  
1169          // Write out elements in order.
1170 <        int mask = elements.length - 1;
1171 <        for (int i = head; i != tail; i = (i + 1) & mask)
1172 <            s.writeObject(elements[i]);
1170 >        final Object[] elements = this.elements;
1171 >        final int capacity = elements.length;
1172 >        int i, end, to, todo;
1173 >        todo = (end = (i = head) + size)
1174 >            - (to = (capacity - end >= 0) ? end : capacity);
1175 >        for (;; to = todo, i = 0, todo = 0) {
1176 >            for (; i < to; i++)
1177 >                s.writeObject(elements[i]);
1178 >            if (todo == 0) break;
1179 >        }
1180      }
1181  
1182      /**
1183       * Reconstitutes this deque from a stream (that is, deserializes it).
1184 +     * @param s the stream
1185 +     * @throws ClassNotFoundException if the class of a serialized object
1186 +     *         could not be found
1187 +     * @throws java.io.IOException if an I/O error occurs
1188       */
1189      private void readObject(java.io.ObjectInputStream s)
1190              throws java.io.IOException, ClassNotFoundException {
1191          s.defaultReadObject();
1192  
1193          // Read in size and allocate array
1194 <        int size = s.readInt();
838 <        allocateElements(size);
839 <        head = 0;
840 <        tail = size;
1194 >        elements = new Object[size = s.readInt()];
1195  
1196          // Read in all elements in the proper order.
1197          for (int i = 0; i < size; i++)
1198              elements[i] = s.readObject();
1199      }
1200 +
1201 +    /** debugging */
1202 +    void checkInvariants() {
1203 +        try {
1204 +            int capacity = elements.length;
1205 +            // assert size >= 0 && size <= capacity;
1206 +            // assert head >= 0;
1207 +            // assert capacity == 0 || head < capacity;
1208 +            // assert size == 0 || elements[head] != null;
1209 +            // assert size == 0 || elements[tail()] != null;
1210 +            // assert size == capacity || elements[dec(head, capacity)] == null;
1211 +            // assert size == capacity || elements[inc(tail(), capacity)] == null;
1212 +        } catch (Throwable t) {
1213 +            System.err.printf("head=%d size=%d capacity=%d%n",
1214 +                              head, size, elements.length);
1215 +            System.err.printf("elements=%s%n",
1216 +                              Arrays.toString(elements));
1217 +            throw t;
1218 +        }
1219 +    }
1220 +
1221   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines