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.5 by dl, Tue Mar 22 01:29:00 2005 UTC vs.
Revision 1.74 by jsr166, Wed Aug 24 21:46:18 2016 UTC

# Line 1 | Line 1
1   /*
2   * Written by Josh Bloch of Google Inc. and released to the public domain,
3 < * as explained at http://creativecommons.org/licenses/publicdomain.
3 > * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
4   */
5  
6   package java.util;
7 < import java.io.*;
7 >
8 > import java.io.Serializable;
9 > import java.util.function.Consumer;
10  
11   /**
12   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 15 | Line 17 | import java.io.*;
17   * {@link Stack} when used as a stack, and faster than {@link LinkedList}
18   * when used as a queue.
19   *
20 < * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
21 < * Exceptions include {@link #remove(Object) remove}, {@link
22 < * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
23 < * removeLastOccurrence}, {@link #contains contains }, {@link #iterator
24 < * iterator.remove()}, and the bulk operations, all of which run in linear
25 < * time.
20 > * <p>Most {@code ArrayDeque} operations run in amortized constant time.
21 > * Exceptions include
22 > * {@link #remove(Object) remove},
23 > * {@link #removeFirstOccurrence removeFirstOccurrence},
24 > * {@link #removeLastOccurrence removeLastOccurrence},
25 > * {@link #contains contains},
26 > * {@link #iterator iterator.remove()},
27 > * and the bulk operations, all of which run in linear time.
28   *
29 < * <p>The iterators returned by this class's <tt>iterator</tt> method are
30 < * <i>fail-fast</i>: If the deque is modified at any time after the iterator
31 < * is created, in any way except through the iterator's own remove method, the
32 < * iterator will generally throw a {@link ConcurrentModificationException}.
33 < * Thus, in the face of concurrent modification, the iterator fails quickly
34 < * and cleanly, rather than risking arbitrary, non-deterministic behavior at
35 < * an undetermined time in the future.
29 > * <p>The iterators returned by this class's {@link #iterator() iterator}
30 > * method are <em>fail-fast</em>: If the deque is modified at any time after
31 > * the iterator is created, in any way except through the iterator's own
32 > * {@code remove} method, the iterator will generally throw a {@link
33 > * ConcurrentModificationException}.  Thus, in the face of concurrent
34 > * modification, the iterator fails quickly and cleanly, rather than risking
35 > * arbitrary, non-deterministic behavior at an undetermined time in the
36 > * future.
37   *
38   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
39   * as it is, generally speaking, impossible to make any hard guarantees in the
40   * presence of unsynchronized concurrent modification.  Fail-fast iterators
41 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
41 > * throw {@code ConcurrentModificationException} on a best-effort basis.
42   * Therefore, it would be wrong to write a program that depended on this
43   * exception for its correctness: <i>the fail-fast behavior of iterators
44   * should be used only to detect bugs.</i>
45   *
46   * <p>This class and its iterator implement all of the
47 < * optional methods of the {@link Collection} and {@link
48 < * Iterator} interfaces.  This class is a member of the <a
49 < * href="{@docRoot}/../guide/collections/index.html"> Java Collections
50 < * Framework</a>.
47 > * <em>optional</em> methods of the {@link Collection} and {@link
48 > * Iterator} interfaces.
49 > *
50 > * <p>This class is a member of the
51 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
52 > * Java Collections Framework</a>.
53   *
54   * @author  Josh Bloch and Doug Lea
55 + * @param <E> the type of elements held in this deque
56   * @since   1.6
49 * @param <E> the type of elements held in this collection
57   */
58   public class ArrayDeque<E> extends AbstractCollection<E>
59                             implements Deque<E>, Cloneable, Serializable
# Line 61 | Line 68 | public class ArrayDeque<E> extends Abstr
68       * other.  We also guarantee that all array cells not holding
69       * deque elements are always null.
70       */
71 <    private transient E[] elements;
71 >    transient Object[] elements; // non-private to simplify nested class access
72  
73      /**
74       * The index of the element at the head of the deque (which is the
75       * element that would be removed by remove() or pop()); or an
76       * arbitrary number equal to tail if the deque is empty.
77       */
78 <    private transient int head;
78 >    transient int head;
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)).
83       */
84 <    private transient int tail;
84 >    transient int tail;
85  
86      /**
87       * The minimum capacity that we'll use for a newly created deque.
# Line 85 | Line 92 | public class ArrayDeque<E> extends Abstr
92      // ******  Array allocation and resizing utilities ******
93  
94      /**
95 <     * Allocate empty array to hold the given number of elements.
95 >     * Allocates empty array to hold the given number of elements.
96       *
97 <     * @param numElements  the number of elements to hold.
97 >     * @param numElements  the number of elements to hold
98       */
99      private void allocateElements(int numElements) {
100          int initialCapacity = MIN_INITIAL_CAPACITY;
# Line 102 | Line 109 | public class ArrayDeque<E> extends Abstr
109              initialCapacity |= (initialCapacity >>> 16);
110              initialCapacity++;
111  
112 <            if (initialCapacity < 0)   // Too many elements, must back off
113 <                initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
112 >            if (initialCapacity < 0)    // Too many elements, must back off
113 >                initialCapacity >>>= 1; // Good luck allocating 2^30 elements
114          }
115 <        elements = (E[]) new Object[initialCapacity];
115 >        elements = new Object[initialCapacity];
116      }
117  
118      /**
119 <     * Double the capacity of this deque.  Call only when full, i.e.,
119 >     * Doubles the capacity of this deque.  Call only when full, i.e.,
120       * when head and tail have wrapped around to become equal.
121       */
122      private void doubleCapacity() {
# Line 123 | Line 130 | public class ArrayDeque<E> extends Abstr
130          Object[] a = new Object[newCapacity];
131          System.arraycopy(elements, p, a, 0, r);
132          System.arraycopy(elements, 0, a, r, p);
133 <        elements = (E[])a;
133 >        elements = a;
134          head = 0;
135          tail = n;
136      }
137  
138      /**
132     * Copy the elements from our element array into the specified array,
133     * in order (from first to last element in the deque).  It is assumed
134     * that the array is large enough to hold all elements in the deque.
135     *
136     * @return its argument
137     */
138    private <T> T[] copyElements(T[] a) {
139        if (head < tail) {
140            System.arraycopy(elements, head, a, 0, size());
141        } else if (head > tail) {
142            int headPortionLen = elements.length - head;
143            System.arraycopy(elements, head, a, 0, headPortionLen);
144            System.arraycopy(elements, 0, a, headPortionLen, tail);
145        }
146        return a;
147    }
148
149    /**
139       * Constructs an empty array deque with an initial capacity
140       * sufficient to hold 16 elements.
141       */
142      public ArrayDeque() {
143 <        elements = (E[]) new Object[16];
143 >        elements = new Object[16];
144      }
145  
146      /**
# Line 186 | Line 175 | public class ArrayDeque<E> extends Abstr
175      /**
176       * Inserts the specified element at the front of this deque.
177       *
178 <     * @param e the element to insert
179 <     * @throws NullPointerException if <tt>e</tt> is null
178 >     * @param e the element to add
179 >     * @throws NullPointerException if the specified element is null
180       */
181      public void addFirst(E e) {
182          if (e == null)
# Line 198 | Line 187 | public class ArrayDeque<E> extends Abstr
187      }
188  
189      /**
190 <     * Inserts the specified element to the end of this deque.
191 <     * This method is equivalent to {@link Collection#add} and
192 <     * {@link #push}.
190 >     * Inserts the specified element at the end of this deque.
191 >     *
192 >     * <p>This method is equivalent to {@link #add}.
193       *
194 <     * @param e the element to insert
195 <     * @throws NullPointerException if <tt>e</tt> is null
194 >     * @param e the element to add
195 >     * @throws NullPointerException if the specified element is null
196       */
197      public void addLast(E e) {
198          if (e == null)
# Line 214 | Line 203 | public class ArrayDeque<E> extends Abstr
203      }
204  
205      /**
217     * Retrieves and removes the first element of this deque, or
218     * <tt>null</tt> if this deque is empty.
219     *
220     * @return the first element of this deque, or <tt>null</tt> if
221     *     this deque is empty
222     */
223    public E pollFirst() {
224        int h = head;
225        E result = elements[h]; // Element is null if deque empty
226        if (result == null)
227            return null;
228        elements[h] = null;     // Must null out slot
229        head = (h + 1) & (elements.length - 1);
230        return result;
231    }
232
233    /**
234     * Retrieves and removes the last element of this deque, or
235     * <tt>null</tt> if this deque is empty.
236     *
237     * @return the last element of this deque, or <tt>null</tt> if
238     *     this deque is empty
239     */
240    public E pollLast() {
241        int t = (tail - 1) & (elements.length - 1);
242        E result = elements[t];
243        if (result == null)
244            return null;
245        elements[t] = null;
246        tail = t;
247        return result;
248    }
249
250    /**
206       * Inserts the specified element at the front of this deque.
207       *
208 <     * @param e the element to insert
209 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerFirst})
210 <     * @throws NullPointerException if <tt>e</tt> is null
208 >     * @param e the element to add
209 >     * @return {@code true} (as specified by {@link Deque#offerFirst})
210 >     * @throws NullPointerException if the specified element is null
211       */
212      public boolean offerFirst(E e) {
213          addFirst(e);
# Line 260 | Line 215 | public class ArrayDeque<E> extends Abstr
215      }
216  
217      /**
218 <     * Inserts the specified element to the end of this deque.
218 >     * Inserts the specified element at the end of this deque.
219       *
220 <     * @param e the element to insert
221 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerLast})
222 <     * @throws NullPointerException if <tt>e</tt> is null
220 >     * @param e the element to add
221 >     * @return {@code true} (as specified by {@link Deque#offerLast})
222 >     * @throws NullPointerException if the specified element is null
223       */
224      public boolean offerLast(E e) {
225          addLast(e);
# Line 272 | Line 227 | public class ArrayDeque<E> extends Abstr
227      }
228  
229      /**
230 <     * Retrieves and removes the first element of this deque.  This method
276 <     * differs from the <tt>pollFirst</tt> method in that it throws an
277 <     * exception if this deque is empty.
278 <     *
279 <     * @return the first element of this deque
280 <     * @throws NoSuchElementException if this deque is empty
230 >     * @throws NoSuchElementException {@inheritDoc}
231       */
232      public E removeFirst() {
233          E x = pollFirst();
# Line 287 | Line 237 | public class ArrayDeque<E> extends Abstr
237      }
238  
239      /**
240 <     * Retrieves and removes the last element of this deque.  This method
291 <     * differs from the <tt>pollLast</tt> method in that it throws an
292 <     * exception if this deque is empty.
293 <     *
294 <     * @return the last element of this deque
295 <     * @throws NoSuchElementException if this deque is empty
240 >     * @throws NoSuchElementException {@inheritDoc}
241       */
242      public E removeLast() {
243          E x = pollLast();
# Line 301 | Line 246 | public class ArrayDeque<E> extends Abstr
246          return x;
247      }
248  
249 <    /**
250 <     * Retrieves, but does not remove, the first element of this deque,
251 <     * returning <tt>null</tt> if this deque is empty.
252 <     *
253 <     * @return the first element of this deque, or <tt>null</tt> if
254 <     *     this deque is empty
255 <     */
256 <    public E peekFirst() {
257 <        return elements[head]; // elements[head] is null if deque empty
249 >    public E pollFirst() {
250 >        final Object[] elements = this.elements;
251 >        final int h = head;
252 >        @SuppressWarnings("unchecked")
253 >        E result = (E) elements[h];
254 >        // Element is null if deque empty
255 >        if (result != null) {
256 >            elements[h] = null; // Must null out slot
257 >            head = (h + 1) & (elements.length - 1);
258 >        }
259 >        return result;
260      }
261  
262 <    /**
263 <     * Retrieves, but does not remove, the last element of this deque,
264 <     * returning <tt>null</tt> if this deque is empty.
265 <     *
266 <     * @return the last element of this deque, or <tt>null</tt> if this deque
267 <     *     is empty
268 <     */
269 <    public E peekLast() {
270 <        return elements[(tail - 1) & (elements.length - 1)];
262 >    public E pollLast() {
263 >        final Object[] elements = this.elements;
264 >        final int t = (tail - 1) & (elements.length - 1);
265 >        @SuppressWarnings("unchecked")
266 >        E result = (E) elements[t];
267 >        if (result != null) {
268 >            elements[t] = null;
269 >            tail = t;
270 >        }
271 >        return result;
272      }
273  
274      /**
275 <     * Retrieves, but does not remove, the first element of this
328 <     * deque.  This method differs from the <tt>peekFirst</tt> method only
329 <     * in that it throws an exception if this deque is empty.
330 <     *
331 <     * @return the first element of this deque
332 <     * @throws NoSuchElementException if this deque is empty
275 >     * @throws NoSuchElementException {@inheritDoc}
276       */
277      public E getFirst() {
278 <        E x = elements[head];
279 <        if (x == null)
278 >        @SuppressWarnings("unchecked")
279 >        E result = (E) elements[head];
280 >        if (result == null)
281              throw new NoSuchElementException();
282 <        return x;
282 >        return result;
283      }
284  
285      /**
286 <     * Retrieves, but does not remove, the last element of this
343 <     * deque.  This method differs from the <tt>peekLast</tt> method only
344 <     * in that it throws an exception if this deque is empty.
345 <     *
346 <     * @return the last element of this deque
347 <     * @throws NoSuchElementException if this deque is empty
286 >     * @throws NoSuchElementException {@inheritDoc}
287       */
288      public E getLast() {
289 <        E x = elements[(tail - 1) & (elements.length - 1)];
290 <        if (x == null)
289 >        @SuppressWarnings("unchecked")
290 >        E result = (E) elements[(tail - 1) & (elements.length - 1)];
291 >        if (result == null)
292              throw new NoSuchElementException();
293 <        return x;
293 >        return result;
294 >    }
295 >
296 >    @SuppressWarnings("unchecked")
297 >    public E peekFirst() {
298 >        // elements[head] is null if deque empty
299 >        return (E) elements[head];
300 >    }
301 >
302 >    @SuppressWarnings("unchecked")
303 >    public E peekLast() {
304 >        return (E) elements[(tail - 1) & (elements.length - 1)];
305      }
306  
307      /**
308       * Removes the first occurrence of the specified element in this
309 <     * deque (when traversing the deque from head to tail).  More
310 <     * formally, removes the first element e such that (o==null ?
311 <     * e==null : o.equals(e)). If the deque does not contain the
312 <     * element, it is unchanged.
309 >     * deque (when traversing the deque from head to tail).
310 >     * If the deque does not contain the element, it is unchanged.
311 >     * More formally, removes the first element {@code e} such that
312 >     * {@code o.equals(e)} (if such an element exists).
313 >     * Returns {@code true} if this deque contained the specified element
314 >     * (or equivalently, if this deque changed as a result of the call).
315       *
316       * @param o element to be removed from this deque, if present
317 <     * @return <tt>true</tt> if the deque contained the specified element
317 >     * @return {@code true} if the deque contained the specified element
318       */
319      public boolean removeFirstOccurrence(Object o) {
320 <        if (o == null)
321 <            return false;
322 <        int mask = elements.length - 1;
323 <        int i = head;
324 <        E x;
325 <        while ( (x = elements[i]) != null) {
326 <            if (o.equals(x)) {
327 <                delete(i);
375 <                return true;
320 >        if (o != null) {
321 >            int mask = elements.length - 1;
322 >            int i = head;
323 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
324 >                if (o.equals(x)) {
325 >                    delete(i);
326 >                    return true;
327 >                }
328              }
377            i = (i + 1) & mask;
329          }
330          return false;
331      }
332  
333      /**
334       * Removes the last occurrence of the specified element in this
335 <     * deque (when traversing the deque from head to tail). More
336 <     * formally, removes the last element e such that (o==null ?
337 <     * e==null : o.equals(e)). If the deque
338 <     * does not contain the element, it is unchanged.
335 >     * deque (when traversing the deque from head to tail).
336 >     * If the deque does not contain the element, it is unchanged.
337 >     * More formally, removes the last element {@code e} such that
338 >     * {@code o.equals(e)} (if such an element exists).
339 >     * Returns {@code true} if this deque contained the specified element
340 >     * (or equivalently, if this deque changed as a result of the call).
341       *
342       * @param o element to be removed from this deque, if present
343 <     * @return <tt>true</tt> if the deque contained the specified element
343 >     * @return {@code true} if the deque contained the specified element
344       */
345      public boolean removeLastOccurrence(Object o) {
346 <        if (o == null)
347 <            return false;
348 <        int mask = elements.length - 1;
349 <        int i = (tail - 1) & mask;
350 <        E x;
351 <        while ( (x = elements[i]) != null) {
352 <            if (o.equals(x)) {
353 <                delete(i);
401 <                return true;
346 >        if (o != null) {
347 >            int mask = elements.length - 1;
348 >            int i = (tail - 1) & mask;
349 >            for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
350 >                if (o.equals(x)) {
351 >                    delete(i);
352 >                    return true;
353 >                }
354              }
403            i = (i - 1) & mask;
355          }
356          return false;
357      }
# Line 408 | Line 359 | public class ArrayDeque<E> extends Abstr
359      // *** Queue methods ***
360  
361      /**
362 <     * Inserts the specified element to the end of this deque.
412 <     *
413 <     * <p>This method is equivalent to {@link #offerLast}.
414 <     *
415 <     * @param e the element to insert
416 <     * @return <tt>true</tt> (as per the spec for {@link Queue#offer})
417 <     * @throws NullPointerException if <tt>e</tt> is null
418 <     */
419 <    public boolean offer(E e) {
420 <        return offerLast(e);
421 <    }
422 <
423 <    /**
424 <     * Inserts the specified element to the end of this deque.
362 >     * Inserts the specified element at the end of this deque.
363       *
364       * <p>This method is equivalent to {@link #addLast}.
365       *
366 <     * @param e the element to insert
367 <     * @return <tt>true</tt> (as per the spec for {@link Collection#add})
368 <     * @throws NullPointerException if <tt>e</tt> is null
366 >     * @param e the element to add
367 >     * @return {@code true} (as specified by {@link Collection#add})
368 >     * @throws NullPointerException if the specified element is null
369       */
370      public boolean add(E e) {
371          addLast(e);
# Line 435 | Line 373 | public class ArrayDeque<E> extends Abstr
373      }
374  
375      /**
376 <     * Retrieves and removes the head of the queue represented by
439 <     * this deque, or <tt>null</tt> if this deque is empty.  In other words,
440 <     * retrieves and removes the first element of this deque, or <tt>null</tt>
441 <     * if this deque is empty.
376 >     * Inserts the specified element at the end of this deque.
377       *
378 <     * <p>This method is equivalent to {@link #pollFirst}.
378 >     * <p>This method is equivalent to {@link #offerLast}.
379       *
380 <     * @return the first element of this deque, or <tt>null</tt> if
381 <     *     this deque is empty
380 >     * @param e the element to add
381 >     * @return {@code true} (as specified by {@link Queue#offer})
382 >     * @throws NullPointerException if the specified element is null
383       */
384 <    public E poll() {
385 <        return pollFirst();
384 >    public boolean offer(E e) {
385 >        return offerLast(e);
386      }
387  
388      /**
389       * Retrieves and removes the head of the queue represented by this deque.
390 <     * This method differs from the <tt>poll</tt> method in that it throws an
390 >     *
391 >     * This method differs from {@link #poll poll} only in that it throws an
392       * exception if this deque is empty.
393       *
394       * <p>This method is equivalent to {@link #removeFirst}.
395       *
396       * @return the head of the queue represented by this deque
397 <     * @throws NoSuchElementException if this deque is empty
397 >     * @throws NoSuchElementException {@inheritDoc}
398       */
399      public E remove() {
400          return removeFirst();
401      }
402  
403      /**
404 <     * Retrieves, but does not remove, the head of the queue represented by
405 <     * this deque, returning <tt>null</tt> if this deque is empty.
404 >     * Retrieves and removes the head of the queue represented by this deque
405 >     * (in other words, the first element of this deque), or returns
406 >     * {@code null} if this deque is empty.
407       *
408 <     * <p>This method is equivalent to {@link #peekFirst}
408 >     * <p>This method is equivalent to {@link #pollFirst}.
409       *
410       * @return the head of the queue represented by this deque, or
411 <     *     <tt>null</tt> if this deque is empty
411 >     *         {@code null} if this deque is empty
412       */
413 <    public E peek() {
414 <        return peekFirst();
413 >    public E poll() {
414 >        return pollFirst();
415      }
416  
417      /**
418       * Retrieves, but does not remove, the head of the queue represented by
419 <     * this deque.  This method differs from the <tt>peek</tt> method only in
419 >     * this deque.  This method differs from {@link #peek peek} only in
420       * that it throws an exception if this deque is empty.
421       *
422 <     * <p>This method is equivalent to {@link #getFirst}
422 >     * <p>This method is equivalent to {@link #getFirst}.
423       *
424       * @return the head of the queue represented by this deque
425 <     * @throws NoSuchElementException if this deque is empty
425 >     * @throws NoSuchElementException {@inheritDoc}
426       */
427      public E element() {
428          return getFirst();
429      }
430  
431 +    /**
432 +     * Retrieves, but does not remove, the head of the queue represented by
433 +     * this deque, or returns {@code null} if this deque is empty.
434 +     *
435 +     * <p>This method is equivalent to {@link #peekFirst}.
436 +     *
437 +     * @return the head of the queue represented by this deque, or
438 +     *         {@code null} if this deque is empty
439 +     */
440 +    public E peek() {
441 +        return peekFirst();
442 +    }
443 +
444      // *** Stack methods ***
445  
446      /**
# Line 499 | Line 450 | public class ArrayDeque<E> extends Abstr
450       * <p>This method is equivalent to {@link #addFirst}.
451       *
452       * @param e the element to push
453 <     * @throws NullPointerException if <tt>e</tt> is null
453 >     * @throws NullPointerException if the specified element is null
454       */
455      public void push(E e) {
456          addFirst(e);
# Line 512 | Line 463 | public class ArrayDeque<E> extends Abstr
463       * <p>This method is equivalent to {@link #removeFirst()}.
464       *
465       * @return the element at the front of this deque (which is the top
466 <     *     of the stack represented by this deque)
467 <     * @throws NoSuchElementException if this deque is empty
466 >     *         of the stack represented by this deque)
467 >     * @throws NoSuchElementException {@inheritDoc}
468       */
469      public E pop() {
470          return removeFirst();
471      }
472  
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 +
481      /**
482 <     * Remove the element at the specified position in the elements array,
483 <     * adjusting head, tail, and size as necessary.  This can result in
484 <     * motion of elements backwards or forwards in the array.
482 >     * Removes the element at the specified position in the elements array,
483 >     * adjusting head and tail as necessary.  This can result in motion of
484 >     * elements backwards or forwards in the array.
485       *
486       * <p>This method is called delete rather than remove to emphasize
487 <     * that its semantics differ from those of List.remove(int).
487 >     * that its semantics differ from those of {@link List#remove(int)}.
488       *
489       * @return true if elements moved backwards
490       */
491 <    private boolean delete(int i) {
492 <        // Case 1: Deque doesn't wrap
493 <        // Case 2: Deque does wrap and removed element is in the head portion
494 <        if ((head < tail || tail == 0) || i >= head) {
495 <            System.arraycopy(elements, head, elements, head + 1, i - head);
496 <            elements[head] = null;
497 <            head = (head + 1) & (elements.length - 1);
491 >    boolean delete(int i) {
492 >        checkInvariants();
493 >        final Object[] elements = this.elements;
494 >        final int mask = elements.length - 1;
495 >        final int h = head;
496 >        final int t = tail;
497 >        final int front = (i - h) & mask;
498 >        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
505 >        if (front < back) {
506 >            if (h <= i) {
507 >                System.arraycopy(elements, h, elements, h + 1, front);
508 >            } else { // Wrap around
509 >                System.arraycopy(elements, 0, elements, 1, i);
510 >                elements[0] = elements[mask];
511 >                System.arraycopy(elements, h, elements, h + 1, mask - h);
512 >            }
513 >            elements[h] = null;
514 >            head = (h + 1) & mask;
515              return false;
516 +        } else {
517 +            if (i < t) { // Copy the null tail as well
518 +                System.arraycopy(elements, i + 1, elements, i, back);
519 +                tail = t - 1;
520 +            } else { // Wrap around
521 +                System.arraycopy(elements, i + 1, elements, i, mask - i);
522 +                elements[mask] = elements[0];
523 +                System.arraycopy(elements, 1, elements, 0, t);
524 +                tail = (t - 1) & mask;
525 +            }
526 +            return true;
527          }
541
542        // Case 3: Deque wraps and removed element is in the tail portion
543        tail--;
544        System.arraycopy(elements, i + 1, elements, i, tail - i);
545        elements[tail] = null;
546        return true;
528      }
529  
530      // *** Collection Methods ***
# Line 558 | Line 539 | public class ArrayDeque<E> extends Abstr
539      }
540  
541      /**
542 <     * Returns <tt>true</tt> if this collection contains no elements.<p>
542 >     * Returns {@code true} if this deque contains no elements.
543       *
544 <     * @return <tt>true</tt> if this collection contains no elements.
544 >     * @return {@code true} if this deque contains no elements
545       */
546      public boolean isEmpty() {
547          return head == tail;
# Line 572 | Line 553 | public class ArrayDeque<E> extends Abstr
553       * order that elements would be dequeued (via successive calls to
554       * {@link #remove} or popped (via successive calls to {@link #pop}).
555       *
556 <     * @return an <tt>Iterator</tt> over the elements in this deque
556 >     * @return an iterator over the elements in this deque
557       */
558      public Iterator<E> iterator() {
559          return new DeqIterator();
560      }
561  
562 +    public Iterator<E> descendingIterator() {
563 +        return new DescendingIterator();
564 +    }
565 +
566      private class DeqIterator implements Iterator<E> {
567          /**
568           * Index of element to be returned by subsequent call to next.
# Line 601 | Line 586 | public class ArrayDeque<E> extends Abstr
586          }
587  
588          public E next() {
604            E result;
589              if (cursor == fence)
590                  throw new NoSuchElementException();
591 +            @SuppressWarnings("unchecked")
592 +            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 = elements[cursor]) == null)
595 >            if (tail != fence || result == null)
596                  throw new ConcurrentModificationException();
597              lastRet = cursor;
598              cursor = (cursor + 1) & (elements.length - 1);
# Line 616 | Line 602 | public class ArrayDeque<E> extends Abstr
602          public void remove() {
603              if (lastRet < 0)
604                  throw new IllegalStateException();
605 <            if (delete(lastRet))
606 <                cursor--;
605 >            if (delete(lastRet)) { // if left-shifted, undo increment in next()
606 >                cursor = (cursor - 1) & (elements.length - 1);
607 >                fence = tail;
608 >            }
609 >            lastRet = -1;
610 >        }
611 >
612 >        public void forEachRemaining(Consumer<? super E> action) {
613 >            Objects.requireNonNull(action);
614 >            Object[] a = elements;
615 >            int m = a.length - 1, f = fence, i = cursor;
616 >            cursor = f;
617 >            while (i != f) {
618 >                @SuppressWarnings("unchecked") E e = (E)a[i];
619 >                i = (i + 1) & m;
620 >                if (e == null)
621 >                    throw new ConcurrentModificationException();
622 >                action.accept(e);
623 >            }
624 >        }
625 >    }
626 >
627 >    /**
628 >     * This class is nearly a mirror-image of DeqIterator, using tail
629 >     * instead of head for initial cursor, and head instead of tail
630 >     * for fence.
631 >     */
632 >    private class DescendingIterator implements Iterator<E> {
633 >        private int cursor = tail;
634 >        private int fence = head;
635 >        private int lastRet = -1;
636 >
637 >        public boolean hasNext() {
638 >            return cursor != fence;
639 >        }
640 >
641 >        public E next() {
642 >            if (cursor == fence)
643 >                throw new NoSuchElementException();
644 >            cursor = (cursor - 1) & (elements.length - 1);
645 >            @SuppressWarnings("unchecked")
646 >            E result = (E) elements[cursor];
647 >            if (head != fence || result == null)
648 >                throw new ConcurrentModificationException();
649 >            lastRet = cursor;
650 >            return result;
651 >        }
652 >
653 >        public void remove() {
654 >            if (lastRet < 0)
655 >                throw new IllegalStateException();
656 >            if (!delete(lastRet)) {
657 >                cursor = (cursor + 1) & (elements.length - 1);
658 >                fence = head;
659 >            }
660              lastRet = -1;
622            fence = tail;
661          }
662      }
663  
664      /**
665 <     * Returns <tt>true</tt> if this deque contains the specified
666 <     * element.  More formally, returns <tt>true</tt> if and only if this
667 <     * deque contains at least one element <tt>e</tt> such that
630 <     * <tt>e.equals(o)</tt>.
665 >     * Returns {@code true} if this deque contains the specified element.
666 >     * More formally, returns {@code true} if and only if this deque contains
667 >     * at least one element {@code e} such that {@code o.equals(e)}.
668       *
669       * @param o object to be checked for containment in this deque
670 <     * @return <tt>true</tt> if this deque contains the specified element
670 >     * @return {@code true} if this deque contains the specified element
671       */
672      public boolean contains(Object o) {
673 <        if (o == null)
674 <            return false;
675 <        int mask = elements.length - 1;
676 <        int i = head;
677 <        E x;
678 <        while ( (x = elements[i]) != null) {
679 <            if (o.equals(x))
643 <                return true;
644 <            i = (i + 1) & mask;
673 >        if (o != null) {
674 >            int mask = elements.length - 1;
675 >            int i = head;
676 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
677 >                if (o.equals(x))
678 >                    return true;
679 >            }
680          }
681          return false;
682      }
683  
684      /**
685       * Removes a single instance of the specified element from this deque.
686 <     * This method is equivalent to {@link #removeFirstOccurrence}.
686 >     * If the deque does not contain the element, it is unchanged.
687 >     * More formally, removes the first element {@code e} such that
688 >     * {@code o.equals(e)} (if such an element exists).
689 >     * Returns {@code true} if this deque contained the specified element
690 >     * (or equivalently, if this deque changed as a result of the call).
691 >     *
692 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
693       *
694 <     * @param e element to be removed from this deque, if present
695 <     * @return <tt>true</tt> if this deque contained the specified element
694 >     * @param o element to be removed from this deque, if present
695 >     * @return {@code true} if this deque contained the specified element
696       */
697 <    public boolean remove(Object e) {
698 <        return removeFirstOccurrence(e);
697 >    public boolean remove(Object o) {
698 >        return removeFirstOccurrence(o);
699      }
700  
701      /**
702       * Removes all of the elements from this deque.
703 +     * The deque will be empty after this call returns.
704       */
705      public void clear() {
706          int h = head;
# Line 670 | Line 712 | public class ArrayDeque<E> extends Abstr
712              do {
713                  elements[i] = null;
714                  i = (i + 1) & mask;
715 <            } while(i != t);
715 >            } while (i != t);
716          }
717      }
718  
719      /**
720       * Returns an array containing all of the elements in this deque
721 <     * in the correct order.
721 >     * in proper sequence (from first to last element).
722 >     *
723 >     * <p>The returned array will be "safe" in that no references to it are
724 >     * maintained by this deque.  (In other words, this method must allocate
725 >     * a new array).  The caller is thus free to modify the returned array.
726 >     *
727 >     * <p>This method acts as bridge between array-based and collection-based
728 >     * APIs.
729       *
730       * @return an array containing all of the elements in this deque
682     *         in the correct order
731       */
732      public Object[] toArray() {
733 <        return copyElements(new Object[size()]);
733 >        final int head = this.head;
734 >        final int tail = this.tail;
735 >        boolean wrap = (tail < head);
736 >        int end = wrap ? tail + elements.length : tail;
737 >        Object[] a = Arrays.copyOfRange(elements, head, end);
738 >        if (wrap)
739 >            System.arraycopy(elements, 0, a, elements.length - head, tail);
740 >        return a;
741      }
742  
743      /**
744 <     * Returns an array containing all of the elements in this deque in the
745 <     * correct order; the runtime type of the returned array is that of the
746 <     * specified array.  If the deque fits in the specified array, it is
747 <     * returned therein.  Otherwise, a new array is allocated with the runtime
748 <     * type of the specified array and the size of this deque.
744 >     * Returns an array containing all of the elements in this deque in
745 >     * proper sequence (from first to last element); the runtime type of the
746 >     * returned array is that of the specified array.  If the deque fits in
747 >     * the specified array, it is returned therein.  Otherwise, a new array
748 >     * is allocated with the runtime type of the specified array and the
749 >     * size of this deque.
750 >     *
751 >     * <p>If this deque fits in the specified array with room to spare
752 >     * (i.e., the array has more elements than this deque), the element in
753 >     * the array immediately following the end of the deque is set to
754 >     * {@code null}.
755 >     *
756 >     * <p>Like the {@link #toArray()} method, this method acts as bridge between
757 >     * array-based and collection-based APIs.  Further, this method allows
758 >     * precise control over the runtime type of the output array, and may,
759 >     * under certain circumstances, be used to save allocation costs.
760 >     *
761 >     * <p>Suppose {@code x} is a deque known to contain only strings.
762 >     * The following code can be used to dump the deque into a newly
763 >     * allocated array of {@code String}:
764       *
765 <     * <p>If the deque fits in the specified array with room to spare (i.e.,
766 <     * the array has more elements than the deque), the element in the array
767 <     * immediately following the end of the collection is set to <tt>null</tt>.
765 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
766 >     *
767 >     * Note that {@code toArray(new Object[0])} is identical in function to
768 >     * {@code toArray()}.
769       *
770       * @param a the array into which the elements of the deque are to
771 <     *          be stored, if it is big enough; otherwise, a new array of the
772 <     *          same runtime type is allocated for this purpose
773 <     * @return an array containing the elements of the deque
774 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
775 <     *         of the runtime type of every element in this deque
771 >     *          be stored, if it is big enough; otherwise, a new array of the
772 >     *          same runtime type is allocated for this purpose
773 >     * @return an array containing all of the elements in this deque
774 >     * @throws ArrayStoreException if the runtime type of the specified array
775 >     *         is not a supertype of the runtime type of every element in
776 >     *         this deque
777 >     * @throws NullPointerException if the specified array is null
778       */
779 +    @SuppressWarnings("unchecked")
780      public <T> T[] toArray(T[] a) {
781 <        int size = size();
782 <        if (a.length < size)
783 <            a = (T[])java.lang.reflect.Array.newInstance(
784 <                    a.getClass().getComponentType(), size);
785 <        copyElements(a);
786 <        if (a.length > size)
787 <            a[size] = null;
781 >        final int head = this.head;
782 >        final int tail = this.tail;
783 >        boolean wrap = (tail < head);
784 >        int size = (tail - head) + (wrap ? elements.length : 0);
785 >        int firstLeg = size - (wrap ? tail : 0);
786 >        int len = a.length;
787 >        if (size > len) {
788 >            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
789 >                                         a.getClass());
790 >        } else {
791 >            System.arraycopy(elements, head, a, 0, firstLeg);
792 >            if (size < len)
793 >                a[size] = null;
794 >        }
795 >        if (wrap)
796 >            System.arraycopy(elements, 0, a, firstLeg, tail);
797          return a;
798      }
799  
# Line 723 | Line 806 | public class ArrayDeque<E> extends Abstr
806       */
807      public ArrayDeque<E> clone() {
808          try {
809 +            @SuppressWarnings("unchecked")
810              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
811 <            // These two lines are currently faster than cloning the array:
728 <            result.elements = (E[]) new Object[elements.length];
729 <            System.arraycopy(elements, 0, result.elements, 0, elements.length);
811 >            result.elements = Arrays.copyOf(elements, elements.length);
812              return result;
731
813          } catch (CloneNotSupportedException e) {
814              throw new AssertionError();
815          }
816      }
817  
737    /**
738     * Appease the serialization gods.
739     */
818      private static final long serialVersionUID = 2340985798034038923L;
819  
820      /**
821 <     * Serialize this deque.
821 >     * Saves this deque to a stream (that is, serializes it).
822       *
823 <     * @serialData The current size (<tt>int</tt>) of the deque,
823 >     * @param s the stream
824 >     * @throws java.io.IOException if an I/O error occurs
825 >     * @serialData The current size ({@code int}) of the deque,
826       * followed by all of its elements (each an object reference) in
827       * first-to-last order.
828       */
829 <    private void writeObject(ObjectOutputStream s) throws IOException {
829 >    private void writeObject(java.io.ObjectOutputStream s)
830 >            throws java.io.IOException {
831          s.defaultWriteObject();
832  
833          // Write out size
834 <        int size = size();
754 <        s.writeInt(size);
834 >        s.writeInt(size());
835  
836          // Write out elements in order.
757        int i = head;
837          int mask = elements.length - 1;
838 <        for (int j = 0; j < size; j++) {
838 >        for (int i = head; i != tail; i = (i + 1) & mask)
839              s.writeObject(elements[i]);
761            i = (i + 1) & mask;
762        }
840      }
841  
842      /**
843 <     * Deserialize this deque.
843 >     * Reconstitutes this deque from a stream (that is, deserializes it).
844 >     * @param s the stream
845 >     * @throws ClassNotFoundException if the class of a serialized object
846 >     *         could not be found
847 >     * @throws java.io.IOException if an I/O error occurs
848       */
849 <    private void readObject(ObjectInputStream s)
850 <            throws IOException, ClassNotFoundException {
849 >    private void readObject(java.io.ObjectInputStream s)
850 >            throws java.io.IOException, ClassNotFoundException {
851          s.defaultReadObject();
852  
853          // Read in size and allocate array
# Line 777 | Line 858 | public class ArrayDeque<E> extends Abstr
858  
859          // Read in all elements in the proper order.
860          for (int i = 0; i < size; i++)
861 <            elements[i] = (E)s.readObject();
861 >            elements[i] = s.readObject();
862 >    }
863  
864 +    /**
865 +     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
866 +     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
867 +     * deque.
868 +     *
869 +     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
870 +     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
871 +     * {@link Spliterator#NONNULL}.  Overriding implementations should document
872 +     * the reporting of additional characteristic values.
873 +     *
874 +     * @return a {@code Spliterator} over the elements in this deque
875 +     * @since 1.8
876 +     */
877 +    public Spliterator<E> spliterator() {
878 +        return new DeqSpliterator<>(this, -1, -1);
879      }
880 +
881 +    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;
955 +        }
956 +    }
957 +
958   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines