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.2 by dl, Tue Mar 8 12:27:06 2005 UTC vs.
Revision 1.65 by jsr166, Sat Feb 28 20:35:47 2015 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   * @since   1.6
56 < * @param <E> the type of elements held in this collection
56 > * @param <E> the type of elements held in this deque
57   */
58   public class ArrayDeque<E> extends AbstractCollection<E>
59                             implements Deque<E>, Cloneable, Serializable
60   {
61      /**
62 <     * The array in which the elements of in the deque are stored.
62 >     * The array in which the elements of the deque are stored.
63       * The capacity of the deque is the length of this array, which is
64       * always a power of two. The array is never allowed to become
65       * full, except transiently within an addX method where it is
# 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) {  
99 >    private void allocateElements(int numElements) {
100          int initialCapacity = MIN_INITIAL_CAPACITY;
101          // Find the best power of two to hold elements.
102          // Tests "<=" because arrays aren't kept full.
# Line 105 | Line 112 | public class ArrayDeque<E> extends Abstr
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() {
123 <        assert head == tail;
123 >        assert head == tail;
124          int p = head;
125          int n = elements.length;
126          int r = n - p; // number of elements to the right of p
# 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      /**
139 <     * 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 <    /**
150 <     * Constructs an empty array deque with the an initial capacity
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 184 | Line 173 | public class ArrayDeque<E> extends Abstr
173      // terms of these.
174  
175      /**
176 <     * Inserts the specified element to the front this deque.
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)
183              throw new NullPointerException();
184          elements[head = (head - 1) & (elements.length - 1)] = e;
185 <        if (head == tail)
185 >        if (head == tail)
186              doubleCapacity();
187      }
188  
189      /**
190 <     * Inserts the specified element to the end 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      /**
206 <     * 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 <    /**
251 <     * Inserts the specified element to the front this deque.
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 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 >        int h = head;
251 >        @SuppressWarnings("unchecked")
252 >        E result = (E) elements[h];
253 >        // Element is null if deque empty
254 >        if (result != null) {
255 >            elements[h] = null; // Must null out slot
256 >            head = (h + 1) & (elements.length - 1);
257 >        }
258 >        return result;
259      }
260  
261 <    /**
262 <     * Retrieves, but does not remove, the last element of this deque,
263 <     * returning <tt>null</tt> if this deque is empty.
264 <     *
265 <     * @return the last element of this deque, or <tt>null</tt> if this deque
266 <     *     is empty
267 <     */
268 <    public E peekLast() {
269 <        return elements[(tail - 1) & (elements.length - 1)];
261 >    public E pollLast() {
262 >        int t = (tail - 1) & (elements.length - 1);
263 >        @SuppressWarnings("unchecked")
264 >        E result = (E) elements[t];
265 >        if (result != null) {
266 >            elements[t] = null;
267 >            tail = t;
268 >        }
269 >        return result;
270      }
271  
272      /**
273 <     * Retrieves, but does not remove, the first element of this
328 <     * deque.  This method differs from the <tt>peek</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
273 >     * @throws NoSuchElementException {@inheritDoc}
274       */
275      public E getFirst() {
276 <        E x = elements[head];
277 <        if (x == null)
276 >        @SuppressWarnings("unchecked")
277 >        E result = (E) elements[head];
278 >        if (result == null)
279              throw new NoSuchElementException();
280 <        return x;
280 >        return result;
281      }
282  
283      /**
284 <     * Retrieves, but does not remove, the last element of this
343 <     * deque.  This method differs from the <tt>peek</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
284 >     * @throws NoSuchElementException {@inheritDoc}
285       */
286      public E getLast() {
287 <        E x = elements[(tail - 1) & (elements.length - 1)];
288 <        if (x == null)
287 >        @SuppressWarnings("unchecked")
288 >        E result = (E) elements[(tail - 1) & (elements.length - 1)];
289 >        if (result == null)
290              throw new NoSuchElementException();
291 <        return x;
291 >        return result;
292 >    }
293 >
294 >    @SuppressWarnings("unchecked")
295 >    public E peekFirst() {
296 >        // elements[head] is null if deque empty
297 >        return (E) elements[head];
298 >    }
299 >
300 >    @SuppressWarnings("unchecked")
301 >    public E peekLast() {
302 >        return (E) elements[(tail - 1) & (elements.length - 1)];
303      }
304  
305      /**
306       * Removes the first occurrence of the specified element in this
307 <     * deque (when traversing the deque from head to tail).  If the deque
308 <     * does not contain the element, it is unchanged.
307 >     * deque (when traversing the deque from head to tail).
308 >     * If the deque does not contain the element, it is unchanged.
309 >     * More formally, removes the first element {@code e} such that
310 >     * {@code o.equals(e)} (if such an element exists).
311 >     * Returns {@code true} if this deque contained the specified element
312 >     * (or equivalently, if this deque changed as a result of the call).
313       *
314 <     * @param e element to be removed from this deque, if present
315 <     * @return <tt>true</tt> if the deque contained the specified element
314 >     * @param o element to be removed from this deque, if present
315 >     * @return {@code true} if the deque contained the specified element
316       */
317 <    public boolean removeFirstOccurrence(Object e) {
318 <        if (e == null)
319 <            return false;
320 <        int mask = elements.length - 1;
321 <        int i = head;
322 <        E x;
323 <        while ( (x = elements[i]) != null) {
324 <            if (e.equals(x)) {
325 <                delete(i);
373 <                return true;
317 >    public boolean removeFirstOccurrence(Object o) {
318 >        if (o != null) {
319 >            int mask = elements.length - 1;
320 >            int i = head;
321 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
322 >                if (o.equals(x)) {
323 >                    delete(i);
324 >                    return true;
325 >                }
326              }
375            i = (i + 1) & mask;
327          }
328          return false;
329      }
330  
331      /**
332       * Removes the last occurrence of the specified element in this
333 <     * deque (when traversing the deque from head to tail).  If the deque
334 <     * does not contain the element, it is unchanged.
333 >     * deque (when traversing the deque from head to tail).
334 >     * If the deque does not contain the element, it is unchanged.
335 >     * More formally, removes the last element {@code e} such that
336 >     * {@code o.equals(e)} (if such an element exists).
337 >     * Returns {@code true} if this deque contained the specified element
338 >     * (or equivalently, if this deque changed as a result of the call).
339       *
340 <     * @param e element to be removed from this deque, if present
341 <     * @return <tt>true</tt> if the deque contained the specified element
340 >     * @param o element to be removed from this deque, if present
341 >     * @return {@code true} if the deque contained the specified element
342       */
343 <    public boolean removeLastOccurrence(Object e) {
344 <        if (e == null)
345 <            return false;
346 <        int mask = elements.length - 1;
347 <        int i = (tail - 1) & mask;
348 <        E x;
349 <        while ( (x = elements[i]) != null) {
350 <            if (e.equals(x)) {
351 <                delete(i);
397 <                return true;
343 >    public boolean removeLastOccurrence(Object o) {
344 >        if (o != null) {
345 >            int mask = elements.length - 1;
346 >            int i = (tail - 1) & mask;
347 >            for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
348 >                if (o.equals(x)) {
349 >                    delete(i);
350 >                    return true;
351 >                }
352              }
399            i = (i - 1) & mask;
353          }
354          return false;
355      }
# Line 404 | Line 357 | public class ArrayDeque<E> extends Abstr
357      // *** Queue methods ***
358  
359      /**
360 <     * Inserts the specified element to the end of this deque.
408 <     *
409 <     * <p>This method is equivalent to {@link #offerLast}.
410 <     *
411 <     * @param e the element to insert
412 <     * @return <tt>true</tt> (as per the spec for {@link Queue#offer})
413 <     * @throws NullPointerException if <tt>e</tt> is null
414 <     */
415 <    public boolean offer(E e) {
416 <        return offerLast(e);
417 <    }
418 <
419 <    /**
420 <     * Inserts the specified element to the end of this deque.
360 >     * Inserts the specified element at the end of this deque.
361       *
362       * <p>This method is equivalent to {@link #addLast}.
363       *
364 <     * @param e the element to insert
365 <     * @return <tt>true</tt> (as per the spec for {@link Collection#add})
366 <     * @throws NullPointerException if <tt>e</tt> is null
364 >     * @param e the element to add
365 >     * @return {@code true} (as specified by {@link Collection#add})
366 >     * @throws NullPointerException if the specified element is null
367       */
368      public boolean add(E e) {
369          addLast(e);
# Line 431 | Line 371 | public class ArrayDeque<E> extends Abstr
371      }
372  
373      /**
374 <     * Retrieves and removes the head of the queue represented by
435 <     * this deque, or <tt>null</tt> if this deque is empty.  In other words,
436 <     * retrieves and removes the first element of this deque, or <tt>null</tt>
437 <     * if this deque is empty.
374 >     * Inserts the specified element at the end of this deque.
375       *
376 <     * <p>This method is equivalent to {@link #pollFirst}.
376 >     * <p>This method is equivalent to {@link #offerLast}.
377       *
378 <     * @return the first element of this deque, or <tt>null</tt> if
379 <     *     this deque is empty
378 >     * @param e the element to add
379 >     * @return {@code true} (as specified by {@link Queue#offer})
380 >     * @throws NullPointerException if the specified element is null
381       */
382 <    public E poll() {
383 <        return pollFirst();
382 >    public boolean offer(E e) {
383 >        return offerLast(e);
384      }
385  
386      /**
387       * Retrieves and removes the head of the queue represented by this deque.
388 <     * This method differs from the <tt>poll</tt> method in that it throws an
388 >     *
389 >     * This method differs from {@link #poll poll} only in that it throws an
390       * exception if this deque is empty.
391       *
392       * <p>This method is equivalent to {@link #removeFirst}.
393       *
394       * @return the head of the queue represented by this deque
395 <     * @throws NoSuchElementException if this deque is empty
395 >     * @throws NoSuchElementException {@inheritDoc}
396       */
397      public E remove() {
398          return removeFirst();
399      }
400  
401      /**
402 <     * Retrieves, but does not remove, the head of the queue represented by
403 <     * this deque, returning <tt>null</tt> if this deque is empty.
402 >     * Retrieves and removes the head of the queue represented by this deque
403 >     * (in other words, the first element of this deque), or returns
404 >     * {@code null} if this deque is empty.
405       *
406 <     * <p>This method is equivalent to {@link #peekFirst}
406 >     * <p>This method is equivalent to {@link #pollFirst}.
407       *
408       * @return the head of the queue represented by this deque, or
409 <     *     <tt>null</tt> if this deque is empty
409 >     *         {@code null} if this deque is empty
410       */
411 <    public E peek() {
412 <        return peekFirst();
411 >    public E poll() {
412 >        return pollFirst();
413      }
414  
415      /**
416       * Retrieves, but does not remove, the head of the queue represented by
417 <     * this deque.  This method differs from the <tt>peek</tt> method only in
417 >     * this deque.  This method differs from {@link #peek peek} only in
418       * that it throws an exception if this deque is empty.
419       *
420 <     * <p>This method is equivalent to {@link #getFirst}
420 >     * <p>This method is equivalent to {@link #getFirst}.
421       *
422       * @return the head of the queue represented by this deque
423 <     * @throws NoSuchElementException if this deque is empty
423 >     * @throws NoSuchElementException {@inheritDoc}
424       */
425      public E element() {
426          return getFirst();
427      }
428  
429 +    /**
430 +     * Retrieves, but does not remove, the head of the queue represented by
431 +     * this deque, or returns {@code null} if this deque is empty.
432 +     *
433 +     * <p>This method is equivalent to {@link #peekFirst}.
434 +     *
435 +     * @return the head of the queue represented by this deque, or
436 +     *         {@code null} if this deque is empty
437 +     */
438 +    public E peek() {
439 +        return peekFirst();
440 +    }
441 +
442      // *** Stack methods ***
443  
444      /**
445       * Pushes an element onto the stack represented by this deque.  In other
446 <     * words, inserts the element to the front this deque.
446 >     * words, inserts the element at the front of this deque.
447       *
448       * <p>This method is equivalent to {@link #addFirst}.
449       *
450       * @param e the element to push
451 <     * @throws NullPointerException if <tt>e</tt> is null
451 >     * @throws NullPointerException if the specified element is null
452       */
453      public void push(E e) {
454          addFirst(e);
# Line 508 | Line 461 | public class ArrayDeque<E> extends Abstr
461       * <p>This method is equivalent to {@link #removeFirst()}.
462       *
463       * @return the element at the front of this deque (which is the top
464 <     *     of the stack represented by this deque)
465 <     * @throws NoSuchElementException if this deque is empty
464 >     *         of the stack represented by this deque)
465 >     * @throws NoSuchElementException {@inheritDoc}
466       */
467      public E pop() {
468          return removeFirst();
469      }
470  
471 +    private void checkInvariants() {
472 +        assert elements[tail] == null;
473 +        assert head == tail ? elements[head] == null :
474 +            (elements[head] != null &&
475 +             elements[(tail - 1) & (elements.length - 1)] != null);
476 +        assert elements[(head - 1) & (elements.length - 1)] == null;
477 +    }
478 +
479      /**
480 <     * Remove the element at the specified position in the elements array,
481 <     * adjusting head, tail, and size as necessary.  This can result in
482 <     * motion of elements backwards or forwards in the array.
483 <     *
484 <     * <p>This method is called delete rather than remove to emphasize the
485 <     * that its semantics differ from those of List.remove(int).
486 <     *
480 >     * Removes the element at the specified position in the elements array,
481 >     * adjusting head and tail as necessary.  This can result in motion of
482 >     * elements backwards or forwards in the array.
483 >     *
484 >     * <p>This method is called delete rather than remove to emphasize
485 >     * that its semantics differ from those of {@link List#remove(int)}.
486 >     *
487       * @return true if elements moved backwards
488       */
489      private boolean delete(int i) {
490 <        // Case 1: Deque doesn't wrap
491 <        // Case 2: Deque does wrap and removed element is in the head portion
492 <        if ((head < tail || tail == 0) || i >= head) {
493 <            System.arraycopy(elements, head, elements, head + 1, i - head);
494 <            elements[head] = null;
495 <            head = (head + 1) & (elements.length - 1);
490 >        checkInvariants();
491 >        final Object[] elements = this.elements;
492 >        final int mask = elements.length - 1;
493 >        final int h = head;
494 >        final int t = tail;
495 >        final int front = (i - h) & mask;
496 >        final int back  = (t - i) & mask;
497 >
498 >        // Invariant: head <= i < tail mod circularity
499 >        if (front >= ((t - h) & mask))
500 >            throw new ConcurrentModificationException();
501 >
502 >        // Optimize for least element motion
503 >        if (front < back) {
504 >            if (h <= i) {
505 >                System.arraycopy(elements, h, elements, h + 1, front);
506 >            } else { // Wrap around
507 >                System.arraycopy(elements, 0, elements, 1, i);
508 >                elements[0] = elements[mask];
509 >                System.arraycopy(elements, h, elements, h + 1, mask - h);
510 >            }
511 >            elements[h] = null;
512 >            head = (h + 1) & mask;
513              return false;
514 +        } else {
515 +            if (i < t) { // Copy the null tail as well
516 +                System.arraycopy(elements, i + 1, elements, i, back);
517 +                tail = t - 1;
518 +            } else { // Wrap around
519 +                System.arraycopy(elements, i + 1, elements, i, mask - i);
520 +                elements[mask] = elements[0];
521 +                System.arraycopy(elements, 1, elements, 0, t);
522 +                tail = (t - 1) & mask;
523 +            }
524 +            return true;
525          }
537
538        // Case 3: Deque wraps and removed element is in the tail portion
539        tail--;
540        System.arraycopy(elements, i + 1, elements, i, tail - i);
541        elements[tail] = null;
542        return true;
526      }
527  
528      // *** Collection Methods ***
# Line 554 | Line 537 | public class ArrayDeque<E> extends Abstr
537      }
538  
539      /**
540 <     * Returns <tt>true</tt> if this collection contains no elements.<p>
540 >     * Returns {@code true} if this deque contains no elements.
541       *
542 <     * @return <tt>true</tt> if this collection contains no elements.
542 >     * @return {@code true} if this deque contains no elements
543       */
544      public boolean isEmpty() {
545          return head == tail;
# Line 567 | Line 550 | public class ArrayDeque<E> extends Abstr
550       * will be ordered from first (head) to last (tail).  This is the same
551       * order that elements would be dequeued (via successive calls to
552       * {@link #remove} or popped (via successive calls to {@link #pop}).
553 <     *
554 <     * @return an <tt>Iterator</tt> over the elements in this deque
553 >     *
554 >     * @return an iterator over the elements in this deque
555       */
556      public Iterator<E> iterator() {
557          return new DeqIterator();
558      }
559  
560 +    public Iterator<E> descendingIterator() {
561 +        return new DescendingIterator();
562 +    }
563 +
564      private class DeqIterator implements Iterator<E> {
565          /**
566           * Index of element to be returned by subsequent call to next.
# Line 597 | Line 584 | public class ArrayDeque<E> extends Abstr
584          }
585  
586          public E next() {
600            E result;
587              if (cursor == fence)
588                  throw new NoSuchElementException();
589 +            @SuppressWarnings("unchecked")
590 +            E result = (E) elements[cursor];
591              // This check doesn't catch all possible comodifications,
592              // but does catch the ones that corrupt traversal
593 <            if (tail != fence || (result = elements[cursor]) == null)
593 >            if (tail != fence || result == null)
594                  throw new ConcurrentModificationException();
595              lastRet = cursor;
596              cursor = (cursor + 1) & (elements.length - 1);
# Line 612 | Line 600 | public class ArrayDeque<E> extends Abstr
600          public void remove() {
601              if (lastRet < 0)
602                  throw new IllegalStateException();
603 <            if (delete(lastRet))
604 <                cursor--;
603 >            if (delete(lastRet)) { // if left-shifted, undo increment in next()
604 >                cursor = (cursor - 1) & (elements.length - 1);
605 >                fence = tail;
606 >            }
607              lastRet = -1;
618            fence = tail;
608          }
609      }
610  
611      /**
612 <     * Returns <tt>true</tt> if this deque contains the specified
613 <     * element.  More formally, returns <tt>true</tt> if and only if this
614 <     * deque contains at least one element <tt>e</tt> such that
615 <     * <tt>e.equals(o)</tt>.
612 >     * This class is nearly a mirror-image of DeqIterator, using tail
613 >     * instead of head for initial cursor, and head instead of tail
614 >     * for fence.
615 >     */
616 >    private class DescendingIterator implements Iterator<E> {
617 >        private int cursor = tail;
618 >        private int fence = head;
619 >        private int lastRet = -1;
620 >
621 >        public boolean hasNext() {
622 >            return cursor != fence;
623 >        }
624 >
625 >        public E next() {
626 >            if (cursor == fence)
627 >                throw new NoSuchElementException();
628 >            cursor = (cursor - 1) & (elements.length - 1);
629 >            @SuppressWarnings("unchecked")
630 >            E result = (E) elements[cursor];
631 >            if (head != fence || result == null)
632 >                throw new ConcurrentModificationException();
633 >            lastRet = cursor;
634 >            return result;
635 >        }
636 >
637 >        public void remove() {
638 >            if (lastRet < 0)
639 >                throw new IllegalStateException();
640 >            if (!delete(lastRet)) {
641 >                cursor = (cursor + 1) & (elements.length - 1);
642 >                fence = head;
643 >            }
644 >            lastRet = -1;
645 >        }
646 >    }
647 >
648 >    /**
649 >     * Returns {@code true} if this deque contains the specified element.
650 >     * More formally, returns {@code true} if and only if this deque contains
651 >     * at least one element {@code e} such that {@code o.equals(e)}.
652       *
653       * @param o object to be checked for containment in this deque
654 <     * @return <tt>true</tt> if this deque contains the specified element
654 >     * @return {@code true} if this deque contains the specified element
655       */
656      public boolean contains(Object o) {
657 <        if (o == null)
658 <            return false;
659 <        int mask = elements.length - 1;
660 <        int i = head;
661 <        E x;
662 <        while ( (x = elements[i]) != null) {
663 <            if (o.equals(x))
639 <                return true;
640 <            i = (i + 1) & mask;
657 >        if (o != null) {
658 >            int mask = elements.length - 1;
659 >            int i = head;
660 >            for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
661 >                if (o.equals(x))
662 >                    return true;
663 >            }
664          }
665          return false;
666      }
667  
668      /**
669       * Removes a single instance of the specified element from this deque.
670 <     * This method is equivalent to {@link #removeFirstOccurrence}.
670 >     * If the deque does not contain the element, it is unchanged.
671 >     * More formally, removes the first element {@code e} such that
672 >     * {@code o.equals(e)} (if such an element exists).
673 >     * Returns {@code true} if this deque contained the specified element
674 >     * (or equivalently, if this deque changed as a result of the call).
675 >     *
676 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
677       *
678 <     * @param e element to be removed from this deque, if present
679 <     * @return <tt>true</tt> if this deque contained the specified element
678 >     * @param o element to be removed from this deque, if present
679 >     * @return {@code true} if this deque contained the specified element
680       */
681 <    public boolean remove(Object e) {
682 <        return removeFirstOccurrence(e);
681 >    public boolean remove(Object o) {
682 >        return removeFirstOccurrence(o);
683      }
684  
685      /**
686       * Removes all of the elements from this deque.
687 +     * The deque will be empty after this call returns.
688       */
689      public void clear() {
690          int h = head;
# Line 666 | Line 696 | public class ArrayDeque<E> extends Abstr
696              do {
697                  elements[i] = null;
698                  i = (i + 1) & mask;
699 <            } while(i != t);
699 >            } while (i != t);
700          }
701      }
702  
703      /**
704 <     * Returns an array containing all of the elements in this list
705 <     * in the correct order.
704 >     * Returns an array containing all of the elements in this deque
705 >     * in proper sequence (from first to last element).
706 >     *
707 >     * <p>The returned array will be "safe" in that no references to it are
708 >     * maintained by this deque.  (In other words, this method must allocate
709 >     * a new array).  The caller is thus free to modify the returned array.
710       *
711 <     * @return an array containing all of the elements in this list
712 <     *         in the correct order
711 >     * <p>This method acts as bridge between array-based and collection-based
712 >     * APIs.
713 >     *
714 >     * @return an array containing all of the elements in this deque
715       */
716      public Object[] toArray() {
717 <        return copyElements(new Object[size()]);
717 >        final int head = this.head;
718 >        final int tail = this.tail;
719 >        boolean wrap = (tail < head);
720 >        int end = wrap ? tail + elements.length : tail;
721 >        Object[] a = Arrays.copyOfRange(elements, head, end);
722 >        if (wrap)
723 >            System.arraycopy(elements, 0, a, elements.length - head, tail);
724 >        return a;
725      }
726  
727      /**
728 <     * Returns an array containing all of the elements in this deque in the
729 <     * correct order; the runtime type of the returned array is that of the
730 <     * specified array.  If the deque fits in the specified array, it is
731 <     * returned therein.  Otherwise, a new array is allocated with the runtime
732 <     * type of the specified array and the size of this deque.
728 >     * Returns an array containing all of the elements in this deque in
729 >     * proper sequence (from first to last element); the runtime type of the
730 >     * returned array is that of the specified array.  If the deque fits in
731 >     * the specified array, it is returned therein.  Otherwise, a new array
732 >     * is allocated with the runtime type of the specified array and the
733 >     * size of this deque.
734 >     *
735 >     * <p>If this deque fits in the specified array with room to spare
736 >     * (i.e., the array has more elements than this deque), the element in
737 >     * the array immediately following the end of the deque is set to
738 >     * {@code null}.
739 >     *
740 >     * <p>Like the {@link #toArray()} method, this method acts as bridge between
741 >     * array-based and collection-based APIs.  Further, this method allows
742 >     * precise control over the runtime type of the output array, and may,
743 >     * under certain circumstances, be used to save allocation costs.
744 >     *
745 >     * <p>Suppose {@code x} is a deque known to contain only strings.
746 >     * The following code can be used to dump the deque into a newly
747 >     * allocated array of {@code String}:
748 >     *
749 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
750       *
751 <     * <p>If the deque fits in the specified array with room to spare (i.e.,
752 <     * the array has more elements than the deque), the element in the array
693 <     * immediately following the end of the collection is set to <tt>null</tt>.
751 >     * Note that {@code toArray(new Object[0])} is identical in function to
752 >     * {@code toArray()}.
753       *
754       * @param a the array into which the elements of the deque are to
755 <     *          be stored, if it is big enough; otherwise, a new array of the
756 <     *          same runtime type is allocated for this purpose
757 <     * @return an array containing the elements of the deque
758 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
759 <     *         of the runtime type of every element in this deque
755 >     *          be stored, if it is big enough; otherwise, a new array of the
756 >     *          same runtime type is allocated for this purpose
757 >     * @return an array containing all of the elements in this deque
758 >     * @throws ArrayStoreException if the runtime type of the specified array
759 >     *         is not a supertype of the runtime type of every element in
760 >     *         this deque
761 >     * @throws NullPointerException if the specified array is null
762       */
763 +    @SuppressWarnings("unchecked")
764      public <T> T[] toArray(T[] a) {
765 <        int size = size();
766 <        if (a.length < size)
767 <            a = (T[])java.lang.reflect.Array.newInstance(
768 <                    a.getClass().getComponentType(), size);
769 <        copyElements(a);
770 <        if (a.length > size)
771 <            a[size] = null;
765 >        final int head = this.head;
766 >        final int tail = this.tail;
767 >        boolean wrap = (tail < head);
768 >        int size = (tail - head) + (wrap ? elements.length : 0);
769 >        int firstLeg = size - (wrap ? tail : 0);
770 >        int len = a.length;
771 >        if (size > len) {
772 >            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
773 >                                         a.getClass());
774 >        } else {
775 >            System.arraycopy(elements, head, a, 0, firstLeg);
776 >            if (size < len)
777 >                a[size] = null;
778 >        }
779 >        if (wrap)
780 >            System.arraycopy(elements, 0, a, firstLeg, tail);
781          return a;
782      }
783  
# Line 718 | Line 789 | public class ArrayDeque<E> extends Abstr
789       * @return a copy of this deque
790       */
791      public ArrayDeque<E> clone() {
792 <        try {
792 >        try {
793 >            @SuppressWarnings("unchecked")
794              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
795 <            // These two lines are currently faster than cloning the array:
724 <            result.elements = (E[]) new Object[elements.length];
725 <            System.arraycopy(elements, 0, result.elements, 0, elements.length);
795 >            result.elements = Arrays.copyOf(elements, elements.length);
796              return result;
797 <
728 <        } catch (CloneNotSupportedException e) {
797 >        } catch (CloneNotSupportedException e) {
798              throw new AssertionError();
799          }
800      }
801  
733    /**
734     * Appease the serialization gods.
735     */
802      private static final long serialVersionUID = 2340985798034038923L;
803  
804      /**
805 <     * Serialize this deque.
805 >     * Saves this deque to a stream (that is, serializes it).
806       *
807 <     * @serialData The current size (<tt>int</tt>) of the deque,
807 >     * @param s the stream
808 >     * @throws java.io.IOException if an I/O error occurs
809 >     * @serialData The current size ({@code int}) of the deque,
810       * followed by all of its elements (each an object reference) in
811       * first-to-last order.
812       */
813 <    private void writeObject(ObjectOutputStream s) throws IOException {
813 >    private void writeObject(java.io.ObjectOutputStream s)
814 >            throws java.io.IOException {
815          s.defaultWriteObject();
816  
817          // Write out size
818 <        int size = size();
750 <        s.writeInt(size);
818 >        s.writeInt(size());
819  
820          // Write out elements in order.
753        int i = head;
821          int mask = elements.length - 1;
822 <        for (int j = 0; j < size; j++) {
822 >        for (int i = head; i != tail; i = (i + 1) & mask)
823              s.writeObject(elements[i]);
757            i = (i + 1) & mask;
758        }
824      }
825  
826      /**
827 <     * Deserialize this deque.
827 >     * Reconstitutes this deque from a stream (that is, deserializes it).
828 >     * @param s the stream
829 >     * @throws ClassNotFoundException if the class of a serialized object
830 >     *         could not be found
831 >     * @throws java.io.IOException if an I/O error occurs
832       */
833 <    private void readObject(ObjectInputStream s)
834 <            throws IOException, ClassNotFoundException {
833 >    private void readObject(java.io.ObjectInputStream s)
834 >            throws java.io.IOException, ClassNotFoundException {
835          s.defaultReadObject();
836  
837          // Read in size and allocate array
# Line 773 | Line 842 | public class ArrayDeque<E> extends Abstr
842  
843          // Read in all elements in the proper order.
844          for (int i = 0; i < size; i++)
845 <            elements[i] = (E)s.readObject();
845 >            elements[i] = s.readObject();
846 >    }
847  
848 +    public Spliterator<E> spliterator() {
849 +        return new DeqSpliterator<E>(this, -1, -1);
850      }
851 +
852 +    static final class DeqSpliterator<E> implements Spliterator<E> {
853 +        private final ArrayDeque<E> deq;
854 +        private int fence;  // -1 until first use
855 +        private int index;  // current index, modified on traverse/split
856 +
857 +        /** Creates new spliterator covering the given array and range */
858 +        DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
859 +            this.deq = deq;
860 +            this.index = origin;
861 +            this.fence = fence;
862 +        }
863 +
864 +        private int getFence() { // force initialization
865 +            int t;
866 +            if ((t = fence) < 0) {
867 +                t = fence = deq.tail;
868 +                index = deq.head;
869 +            }
870 +            return t;
871 +        }
872 +
873 +        public Spliterator<E> trySplit() {
874 +            int t = getFence(), h = index, n = deq.elements.length;
875 +            if (h != t && ((h + 1) & (n - 1)) != t) {
876 +                if (h > t)
877 +                    t += n;
878 +                int m = ((h + t) >>> 1) & (n - 1);
879 +                return new DeqSpliterator<>(deq, h, index = m);
880 +            }
881 +            return null;
882 +        }
883 +
884 +        public void forEachRemaining(Consumer<? super E> consumer) {
885 +            if (consumer == null)
886 +                throw new NullPointerException();
887 +            Object[] a = deq.elements;
888 +            int m = a.length - 1, f = getFence(), i = index;
889 +            index = f;
890 +            while (i != f) {
891 +                @SuppressWarnings("unchecked") E e = (E)a[i];
892 +                i = (i + 1) & m;
893 +                if (e == null)
894 +                    throw new ConcurrentModificationException();
895 +                consumer.accept(e);
896 +            }
897 +        }
898 +
899 +        public boolean tryAdvance(Consumer<? super E> consumer) {
900 +            if (consumer == null)
901 +                throw new NullPointerException();
902 +            Object[] a = deq.elements;
903 +            int m = a.length - 1, f = getFence(), i = index;
904 +            if (i != f) {
905 +                @SuppressWarnings("unchecked") E e = (E)a[i];
906 +                index = (i + 1) & m;
907 +                if (e == null)
908 +                    throw new ConcurrentModificationException();
909 +                consumer.accept(e);
910 +                return true;
911 +            }
912 +            return false;
913 +        }
914 +
915 +        public long estimateSize() {
916 +            int n = getFence() - index;
917 +            if (n < 0)
918 +                n += deq.elements.length;
919 +            return (long) n;
920 +        }
921 +
922 +        @Override
923 +        public int characteristics() {
924 +            return Spliterator.ORDERED | Spliterator.SIZED |
925 +                Spliterator.NONNULL | Spliterator.SUBSIZED;
926 +        }
927 +    }
928 +
929   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines