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.3 by dl, Tue Mar 8 17:52:02 2005 UTC vs.
Revision 1.34 by jsr166, Fri Jun 10 20:58:50 2011 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   /**
9   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 18 | Line 17 | import java.io.*;
17   * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
18   * Exceptions include {@link #remove(Object) remove}, {@link
19   * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
20 < * removeLastOccurrence}, {@link #contains contains }, {@link #iterator
20 > * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
21   * iterator.remove()}, and the bulk operations, all of which run in linear
22   * time.
23   *
24   * <p>The iterators returned by this class's <tt>iterator</tt> method are
25   * <i>fail-fast</i>: If the deque is modified at any time after the iterator
26 < * is created, in any way except through the iterator's own remove method, the
27 < * iterator will generally throw a {@link ConcurrentModificationException}.
28 < * Thus, in the face of concurrent modification, the iterator fails quickly
29 < * and cleanly, rather than risking arbitrary, non-deterministic behavior at
30 < * an undetermined time in the future.
26 > * is created, in any way except through the iterator's own <tt>remove</tt>
27 > * method, the iterator will generally throw a {@link
28 > * ConcurrentModificationException}.  Thus, in the face of concurrent
29 > * modification, the iterator fails quickly and cleanly, rather than risking
30 > * arbitrary, non-deterministic behavior at an undetermined time in the
31 > * future.
32   *
33   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
34   * as it is, generally speaking, impossible to make any hard guarantees in the
35   * presence of unsynchronized concurrent modification.  Fail-fast iterators
36 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
36 > * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
37   * Therefore, it would be wrong to write a program that depended on this
38   * exception for its correctness: <i>the fail-fast behavior of iterators
39   * should be used only to detect bugs.</i>
40   *
41   * <p>This class and its iterator implement all of the
42 < * optional methods of the {@link Collection} and {@link
43 < * Iterator} interfaces.  This class is a member of the <a
44 < * href="{@docRoot}/../guide/collections/index.html"> Java Collections
45 < * Framework</a>.
42 > * <em>optional</em> methods of the {@link Collection} and {@link
43 > * Iterator} interfaces.
44 > *
45 > * <p>This class is a member of the
46 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
47 > * Java Collections Framework</a>.
48   *
49   * @author  Josh Bloch and Doug Lea
50   * @since   1.6
51   * @param <E> the type of elements held in this collection
52   */
53   public class ArrayDeque<E> extends AbstractCollection<E>
54 <                           implements Deque<E>, Cloneable, Serializable
54 >                           implements Deque<E>, Cloneable, java.io.Serializable
55   {
56      /**
57 <     * The array in which the elements of in the deque are stored.
57 >     * The array in which the elements of the deque are stored.
58       * The capacity of the deque is the length of this array, which is
59       * always a power of two. The array is never allowed to become
60       * full, except transiently within an addX method where it is
# Line 61 | Line 63 | public class ArrayDeque<E> extends Abstr
63       * other.  We also guarantee that all array cells not holding
64       * deque elements are always null.
65       */
66 <    private transient E[] elements;
66 >    private transient Object[] elements;
67  
68      /**
69       * The index of the element at the head of the deque (which is the
# Line 87 | Line 89 | public class ArrayDeque<E> extends Abstr
89      /**
90       * Allocate empty array to hold the given number of elements.
91       *
92 <     * @param numElements  the number of elements to hold.
92 >     * @param numElements  the number of elements to hold
93       */
94 <    private void allocateElements(int numElements) {  
94 >    private void allocateElements(int numElements) {
95          int initialCapacity = MIN_INITIAL_CAPACITY;
96          // Find the best power of two to hold elements.
97          // Tests "<=" because arrays aren't kept full.
# Line 105 | Line 107 | public class ArrayDeque<E> extends Abstr
107              if (initialCapacity < 0)   // Too many elements, must back off
108                  initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
109          }
110 <        elements = (E[]) new Object[initialCapacity];
110 >        elements = new Object[initialCapacity];
111      }
112  
113      /**
# Line 113 | Line 115 | public class ArrayDeque<E> extends Abstr
115       * when head and tail have wrapped around to become equal.
116       */
117      private void doubleCapacity() {
118 <        assert head == tail;
118 >        assert head == tail;
119          int p = head;
120          int n = elements.length;
121          int r = n - p; // number of elements to the right of p
# Line 123 | Line 125 | public class ArrayDeque<E> extends Abstr
125          Object[] a = new Object[newCapacity];
126          System.arraycopy(elements, p, a, 0, r);
127          System.arraycopy(elements, 0, a, r, p);
128 <        elements = (E[])a;
128 >        elements = a;
129          head = 0;
130          tail = n;
131      }
132  
133      /**
134 <     * Copy the elements from our element array into the specified array,
134 >     * Copies the elements from our element array into the specified array,
135       * in order (from first to last element in the deque).  It is assumed
136       * that the array is large enough to hold all elements in the deque.
137       *
# Line 147 | Line 149 | public class ArrayDeque<E> extends Abstr
149      }
150  
151      /**
152 <     * Constructs an empty array deque with the an initial capacity
152 >     * Constructs an empty array deque with an initial capacity
153       * sufficient to hold 16 elements.
154       */
155      public ArrayDeque() {
156 <        elements = (E[]) new Object[16];
156 >        elements = new Object[16];
157      }
158  
159      /**
# Line 184 | Line 186 | public class ArrayDeque<E> extends Abstr
186      // terms of these.
187  
188      /**
189 <     * Inserts the specified element to the front this deque.
189 >     * Inserts the specified element at the front of this deque.
190       *
191 <     * @param e the element to insert
192 <     * @throws NullPointerException if <tt>e</tt> is null
191 >     * @param e the element to add
192 >     * @throws NullPointerException if the specified element is null
193       */
194      public void addFirst(E e) {
195          if (e == null)
196              throw new NullPointerException();
197          elements[head = (head - 1) & (elements.length - 1)] = e;
198 <        if (head == tail)
198 >        if (head == tail)
199              doubleCapacity();
200      }
201  
202      /**
203 <     * Inserts the specified element to the end this deque.
204 <     * This method is equivalent to {@link Collection#add} and
205 <     * {@link #push}.
203 >     * Inserts the specified element at the end of this deque.
204 >     *
205 >     * <p>This method is equivalent to {@link #add}.
206       *
207 <     * @param e the element to insert
208 <     * @throws NullPointerException if <tt>e</tt> is null
207 >     * @param e the element to add
208 >     * @throws NullPointerException if the specified element is null
209       */
210      public void addLast(E e) {
211          if (e == null)
# Line 214 | Line 216 | public class ArrayDeque<E> extends Abstr
216      }
217  
218      /**
219 <     * 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.
219 >     * Inserts the specified element at the front of this deque.
220       *
221 <     * @return the last element of this deque, or <tt>null</tt> if
222 <     *     this deque is empty
223 <     */
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.
252 <     *
253 <     * @param e the element to insert
254 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerFirst})
255 <     * @throws NullPointerException if <tt>e</tt> is null
221 >     * @param e the element to add
222 >     * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
223 >     * @throws NullPointerException if the specified element is null
224       */
225      public boolean offerFirst(E e) {
226          addFirst(e);
# Line 260 | Line 228 | public class ArrayDeque<E> extends Abstr
228      }
229  
230      /**
231 <     * Inserts the specified element to the end this deque.
231 >     * Inserts the specified element at the end of this deque.
232       *
233 <     * @param e the element to insert
234 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerLast})
235 <     * @throws NullPointerException if <tt>e</tt> is null
233 >     * @param e the element to add
234 >     * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
235 >     * @throws NullPointerException if the specified element is null
236       */
237      public boolean offerLast(E e) {
238          addLast(e);
# Line 272 | Line 240 | public class ArrayDeque<E> extends Abstr
240      }
241  
242      /**
243 <     * 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
243 >     * @throws NoSuchElementException {@inheritDoc}
244       */
245      public E removeFirst() {
246          E x = pollFirst();
# Line 287 | Line 250 | public class ArrayDeque<E> extends Abstr
250      }
251  
252      /**
253 <     * 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
253 >     * @throws NoSuchElementException {@inheritDoc}
254       */
255      public E removeLast() {
256          E x = pollLast();
# Line 301 | Line 259 | public class ArrayDeque<E> extends Abstr
259          return x;
260      }
261  
262 <    /**
263 <     * Retrieves, but does not remove, the first element of this deque,
264 <     * returning <tt>null</tt> if this deque is empty.
265 <     *
266 <     * @return the first element of this deque, or <tt>null</tt> if
267 <     *     this deque is empty
268 <     */
269 <    public E peekFirst() {
270 <        return elements[head]; // elements[head] is null if deque empty
262 >    public E pollFirst() {
263 >        int h = head;
264 >        @SuppressWarnings("unchecked") E result = (E) elements[h];
265 >        // Element is null if deque empty
266 >        if (result == null)
267 >            return null;
268 >        elements[h] = null;     // Must null out slot
269 >        head = (h + 1) & (elements.length - 1);
270 >        return result;
271      }
272  
273 <    /**
274 <     * Retrieves, but does not remove, the last element of this deque,
275 <     * returning <tt>null</tt> if this deque is empty.
276 <     *
277 <     * @return the last element of this deque, or <tt>null</tt> if this deque
278 <     *     is empty
279 <     */
280 <    public E peekLast() {
323 <        return elements[(tail - 1) & (elements.length - 1)];
273 >    public E pollLast() {
274 >        int t = (tail - 1) & (elements.length - 1);
275 >        @SuppressWarnings("unchecked") E result = (E) elements[t];
276 >        if (result == null)
277 >            return null;
278 >        elements[t] = null;
279 >        tail = t;
280 >        return result;
281      }
282  
283      /**
284 <     * 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
284 >     * @throws NoSuchElementException {@inheritDoc}
285       */
286      public E getFirst() {
287 <        E x = elements[head];
288 <        if (x == null)
287 >        @SuppressWarnings("unchecked") E result = (E) elements[head];
288 >        if (result == null)
289              throw new NoSuchElementException();
290 <        return x;
290 >        return result;
291      }
292  
293      /**
294 <     * 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
294 >     * @throws NoSuchElementException {@inheritDoc}
295       */
296      public E getLast() {
297 <        E x = elements[(tail - 1) & (elements.length - 1)];
298 <        if (x == null)
297 >        @SuppressWarnings("unchecked")
298 >        E result = (E) elements[(tail - 1) & (elements.length - 1)];
299 >        if (result == null)
300              throw new NoSuchElementException();
301 <        return x;
301 >        return result;
302 >    }
303 >
304 >    public E peekFirst() {
305 >        @SuppressWarnings("unchecked") E result = (E) elements[head];
306 >        // elements[head] is null if deque empty
307 >        return result;
308 >    }
309 >
310 >    public E peekLast() {
311 >        @SuppressWarnings("unchecked")
312 >        E result = (E) elements[(tail - 1) & (elements.length - 1)];
313 >        return result;
314      }
315  
316      /**
317       * Removes the first occurrence of the specified element in this
318 <     * deque (when traversing the deque from head to tail).  If the deque
319 <     * does not contain the element, it is unchanged.
318 >     * deque (when traversing the deque from head to tail).
319 >     * If the deque does not contain the element, it is unchanged.
320 >     * More formally, removes the first element <tt>e</tt> such that
321 >     * <tt>o.equals(e)</tt> (if such an element exists).
322 >     * Returns <tt>true</tt> if this deque contained the specified element
323 >     * (or equivalently, if this deque changed as a result of the call).
324       *
325 <     * @param e element to be removed from this deque, if present
325 >     * @param o element to be removed from this deque, if present
326       * @return <tt>true</tt> if the deque contained the specified element
327       */
328 <    public boolean removeFirstOccurrence(Object e) {
329 <        if (e == null)
328 >    public boolean removeFirstOccurrence(Object o) {
329 >        if (o == null)
330              return false;
331          int mask = elements.length - 1;
332          int i = head;
333 <        E x;
333 >        Object x;
334          while ( (x = elements[i]) != null) {
335 <            if (e.equals(x)) {
335 >            if (o.equals(x)) {
336                  delete(i);
337                  return true;
338              }
# Line 379 | Line 343 | public class ArrayDeque<E> extends Abstr
343  
344      /**
345       * Removes the last occurrence of the specified element in this
346 <     * deque (when traversing the deque from head to tail).  If the deque
347 <     * does not contain the element, it is unchanged.
346 >     * deque (when traversing the deque from head to tail).
347 >     * If the deque does not contain the element, it is unchanged.
348 >     * More formally, removes the last element <tt>e</tt> such that
349 >     * <tt>o.equals(e)</tt> (if such an element exists).
350 >     * Returns <tt>true</tt> if this deque contained the specified element
351 >     * (or equivalently, if this deque changed as a result of the call).
352       *
353 <     * @param e element to be removed from this deque, if present
353 >     * @param o element to be removed from this deque, if present
354       * @return <tt>true</tt> if the deque contained the specified element
355       */
356 <    public boolean removeLastOccurrence(Object e) {
357 <        if (e == null)
356 >    public boolean removeLastOccurrence(Object o) {
357 >        if (o == null)
358              return false;
359          int mask = elements.length - 1;
360          int i = (tail - 1) & mask;
361 <        E x;
361 >        Object x;
362          while ( (x = elements[i]) != null) {
363 <            if (e.equals(x)) {
363 >            if (o.equals(x)) {
364                  delete(i);
365                  return true;
366              }
# Line 404 | Line 372 | public class ArrayDeque<E> extends Abstr
372      // *** Queue methods ***
373  
374      /**
375 <     * 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.
375 >     * Inserts the specified element at the end of this deque.
376       *
377       * <p>This method is equivalent to {@link #addLast}.
378       *
379 <     * @param e the element to insert
380 <     * @return <tt>true</tt> (as per the spec for {@link Collection#add})
381 <     * @throws NullPointerException if <tt>e</tt> is null
379 >     * @param e the element to add
380 >     * @return <tt>true</tt> (as specified by {@link Collection#add})
381 >     * @throws NullPointerException if the specified element is null
382       */
383      public boolean add(E e) {
384          addLast(e);
# Line 431 | Line 386 | public class ArrayDeque<E> extends Abstr
386      }
387  
388      /**
389 <     * 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.
389 >     * Inserts the specified element at the end of this deque.
390       *
391 <     * <p>This method is equivalent to {@link #pollFirst}.
391 >     * <p>This method is equivalent to {@link #offerLast}.
392       *
393 <     * @return the first element of this deque, or <tt>null</tt> if
394 <     *     this deque is empty
393 >     * @param e the element to add
394 >     * @return <tt>true</tt> (as specified by {@link Queue#offer})
395 >     * @throws NullPointerException if the specified element is null
396       */
397 <    public E poll() {
398 <        return pollFirst();
397 >    public boolean offer(E e) {
398 >        return offerLast(e);
399      }
400  
401      /**
402       * Retrieves and removes the head of the queue represented by this deque.
403 <     * This method differs from the <tt>poll</tt> method in that it throws an
403 >     *
404 >     * This method differs from {@link #poll poll} only in that it throws an
405       * exception if this deque is empty.
406       *
407       * <p>This method is equivalent to {@link #removeFirst}.
408       *
409       * @return the head of the queue represented by this deque
410 <     * @throws NoSuchElementException if this deque is empty
410 >     * @throws NoSuchElementException {@inheritDoc}
411       */
412      public E remove() {
413          return removeFirst();
414      }
415  
416      /**
417 <     * Retrieves, but does not remove, the head of the queue represented by
418 <     * this deque, returning <tt>null</tt> if this deque is empty.
417 >     * Retrieves and removes the head of the queue represented by this deque
418 >     * (in other words, the first element of this deque), or returns
419 >     * <tt>null</tt> if this deque is empty.
420       *
421 <     * <p>This method is equivalent to {@link #peekFirst}
421 >     * <p>This method is equivalent to {@link #pollFirst}.
422       *
423       * @return the head of the queue represented by this deque, or
424 <     *     <tt>null</tt> if this deque is empty
424 >     *         <tt>null</tt> if this deque is empty
425       */
426 <    public E peek() {
427 <        return peekFirst();
426 >    public E poll() {
427 >        return pollFirst();
428      }
429  
430      /**
431       * Retrieves, but does not remove, the head of the queue represented by
432 <     * this deque.  This method differs from the <tt>peek</tt> method only in
432 >     * this deque.  This method differs from {@link #peek peek} only in
433       * that it throws an exception if this deque is empty.
434       *
435 <     * <p>This method is equivalent to {@link #getFirst}
435 >     * <p>This method is equivalent to {@link #getFirst}.
436       *
437       * @return the head of the queue represented by this deque
438 <     * @throws NoSuchElementException if this deque is empty
438 >     * @throws NoSuchElementException {@inheritDoc}
439       */
440      public E element() {
441          return getFirst();
442      }
443  
444 +    /**
445 +     * Retrieves, but does not remove, the head of the queue represented by
446 +     * this deque, or returns <tt>null</tt> if this deque is empty.
447 +     *
448 +     * <p>This method is equivalent to {@link #peekFirst}.
449 +     *
450 +     * @return the head of the queue represented by this deque, or
451 +     *         <tt>null</tt> if this deque is empty
452 +     */
453 +    public E peek() {
454 +        return peekFirst();
455 +    }
456 +
457      // *** Stack methods ***
458  
459      /**
460       * Pushes an element onto the stack represented by this deque.  In other
461 <     * words, inserts the element to the front this deque.
461 >     * words, inserts the element at the front of this deque.
462       *
463       * <p>This method is equivalent to {@link #addFirst}.
464       *
465       * @param e the element to push
466 <     * @throws NullPointerException if <tt>e</tt> is null
466 >     * @throws NullPointerException if the specified element is null
467       */
468      public void push(E e) {
469          addFirst(e);
# Line 508 | Line 476 | public class ArrayDeque<E> extends Abstr
476       * <p>This method is equivalent to {@link #removeFirst()}.
477       *
478       * @return the element at the front of this deque (which is the top
479 <     *     of the stack represented by this deque)
480 <     * @throws NoSuchElementException if this deque is empty
479 >     *         of the stack represented by this deque)
480 >     * @throws NoSuchElementException {@inheritDoc}
481       */
482      public E pop() {
483          return removeFirst();
484      }
485  
486 +    private void checkInvariants() {
487 +        assert elements[tail] == null;
488 +        assert head == tail ? elements[head] == null :
489 +            (elements[head] != null &&
490 +             elements[(tail - 1) & (elements.length - 1)] != null);
491 +        assert elements[(head - 1) & (elements.length - 1)] == null;
492 +    }
493 +
494      /**
495 <     * Remove the element at the specified position in the elements array,
496 <     * adjusting head, tail, and size as necessary.  This can result in
497 <     * motion of elements backwards or forwards in the array.
498 <     *
499 <     * <p>This method is called delete rather than remove to emphasize
500 <     * that its semantics differ from those of List.remove(int).
501 <     *
495 >     * Removes the element at the specified position in the elements array,
496 >     * adjusting head and tail as necessary.  This can result in motion of
497 >     * elements backwards or forwards in the array.
498 >     *
499 >     * <p>This method is called delete rather than remove to emphasize
500 >     * that its semantics differ from those of {@link List#remove(int)}.
501 >     *
502       * @return true if elements moved backwards
503       */
504      private boolean delete(int i) {
505 <        // Case 1: Deque doesn't wrap
506 <        // Case 2: Deque does wrap and removed element is in the head portion
507 <        if ((head < tail || tail == 0) || i >= head) {
508 <            System.arraycopy(elements, head, elements, head + 1, i - head);
509 <            elements[head] = null;
510 <            head = (head + 1) & (elements.length - 1);
505 >        checkInvariants();
506 >        final Object[] elements = this.elements;
507 >        final int mask = elements.length - 1;
508 >        final int h = head;
509 >        final int t = tail;
510 >        final int front = (i - h) & mask;
511 >        final int back  = (t - i) & mask;
512 >
513 >        // Invariant: head <= i < tail mod circularity
514 >        if (front >= ((t - h) & mask))
515 >            throw new ConcurrentModificationException();
516 >
517 >        // Optimize for least element motion
518 >        if (front < back) {
519 >            if (h <= i) {
520 >                System.arraycopy(elements, h, elements, h + 1, front);
521 >            } else { // Wrap around
522 >                System.arraycopy(elements, 0, elements, 1, i);
523 >                elements[0] = elements[mask];
524 >                System.arraycopy(elements, h, elements, h + 1, mask - h);
525 >            }
526 >            elements[h] = null;
527 >            head = (h + 1) & mask;
528              return false;
529 +        } else {
530 +            if (i < t) { // Copy the null tail as well
531 +                System.arraycopy(elements, i + 1, elements, i, back);
532 +                tail = t - 1;
533 +            } else { // Wrap around
534 +                System.arraycopy(elements, i + 1, elements, i, mask - i);
535 +                elements[mask] = elements[0];
536 +                System.arraycopy(elements, 1, elements, 0, t);
537 +                tail = (t - 1) & mask;
538 +            }
539 +            return true;
540          }
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;
541      }
542  
543      // *** Collection Methods ***
# Line 554 | Line 552 | public class ArrayDeque<E> extends Abstr
552      }
553  
554      /**
555 <     * Returns <tt>true</tt> if this collection contains no elements.<p>
555 >     * Returns <tt>true</tt> if this deque contains no elements.
556       *
557 <     * @return <tt>true</tt> if this collection contains no elements.
557 >     * @return <tt>true</tt> if this deque contains no elements
558       */
559      public boolean isEmpty() {
560          return head == tail;
# Line 567 | Line 565 | public class ArrayDeque<E> extends Abstr
565       * will be ordered from first (head) to last (tail).  This is the same
566       * order that elements would be dequeued (via successive calls to
567       * {@link #remove} or popped (via successive calls to {@link #pop}).
568 <     *
569 <     * @return an <tt>Iterator</tt> over the elements in this deque
568 >     *
569 >     * @return an iterator over the elements in this deque
570       */
571      public Iterator<E> iterator() {
572          return new DeqIterator();
573      }
574  
575 +    public Iterator<E> descendingIterator() {
576 +        return new DescendingIterator();
577 +    }
578 +
579      private class DeqIterator implements Iterator<E> {
580          /**
581           * Index of element to be returned by subsequent call to next.
# Line 597 | Line 599 | public class ArrayDeque<E> extends Abstr
599          }
600  
601          public E next() {
600            E result;
602              if (cursor == fence)
603                  throw new NoSuchElementException();
604 +            @SuppressWarnings("unchecked") E result = (E) elements[cursor];
605              // This check doesn't catch all possible comodifications,
606              // but does catch the ones that corrupt traversal
607 <            if (tail != fence || (result = elements[cursor]) == null)
607 >            if (tail != fence || result == null)
608                  throw new ConcurrentModificationException();
609              lastRet = cursor;
610              cursor = (cursor + 1) & (elements.length - 1);
# Line 612 | Line 614 | public class ArrayDeque<E> extends Abstr
614          public void remove() {
615              if (lastRet < 0)
616                  throw new IllegalStateException();
617 <            if (delete(lastRet))
618 <                cursor--;
617 >            if (delete(lastRet)) { // if left-shifted, undo increment in next()
618 >                cursor = (cursor - 1) & (elements.length - 1);
619 >                fence = tail;
620 >            }
621 >            lastRet = -1;
622 >        }
623 >    }
624 >
625 >    private class DescendingIterator implements Iterator<E> {
626 >        /*
627 >         * This class is nearly a mirror-image of DeqIterator, using
628 >         * tail instead of head for initial cursor, and head instead of
629 >         * tail for fence.
630 >         */
631 >        private int cursor = tail;
632 >        private int fence = head;
633 >        private int lastRet = -1;
634 >
635 >        public boolean hasNext() {
636 >            return cursor != fence;
637 >        }
638 >
639 >        public E next() {
640 >            if (cursor == fence)
641 >                throw new NoSuchElementException();
642 >            cursor = (cursor - 1) & (elements.length - 1);
643 >            @SuppressWarnings("unchecked") E result = (E) elements[cursor];
644 >            if (head != fence || result == null)
645 >                throw new ConcurrentModificationException();
646 >            lastRet = cursor;
647 >            return result;
648 >        }
649 >
650 >        public void remove() {
651 >            if (lastRet < 0)
652 >                throw new IllegalStateException();
653 >            if (!delete(lastRet)) {
654 >                cursor = (cursor + 1) & (elements.length - 1);
655 >                fence = head;
656 >            }
657              lastRet = -1;
618            fence = tail;
658          }
659      }
660  
661      /**
662 <     * Returns <tt>true</tt> if this deque contains the specified
663 <     * element.  More formally, returns <tt>true</tt> if and only if this
664 <     * deque contains at least one element <tt>e</tt> such that
626 <     * <tt>e.equals(o)</tt>.
662 >     * Returns <tt>true</tt> if this deque contains the specified element.
663 >     * More formally, returns <tt>true</tt> if and only if this deque contains
664 >     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
665       *
666       * @param o object to be checked for containment in this deque
667       * @return <tt>true</tt> if this deque contains the specified element
# Line 633 | Line 671 | public class ArrayDeque<E> extends Abstr
671              return false;
672          int mask = elements.length - 1;
673          int i = head;
674 <        E x;
674 >        Object x;
675          while ( (x = elements[i]) != null) {
676              if (o.equals(x))
677                  return true;
# Line 644 | Line 682 | public class ArrayDeque<E> extends Abstr
682  
683      /**
684       * Removes a single instance of the specified element from this deque.
685 <     * This method is equivalent to {@link #removeFirstOccurrence}.
685 >     * If the deque does not contain the element, it is unchanged.
686 >     * More formally, removes the first element <tt>e</tt> such that
687 >     * <tt>o.equals(e)</tt> (if such an element exists).
688 >     * Returns <tt>true</tt> if this deque contained the specified element
689 >     * (or equivalently, if this deque changed as a result of the call).
690 >     *
691 >     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
692       *
693 <     * @param e element to be removed from this deque, if present
693 >     * @param o element to be removed from this deque, if present
694       * @return <tt>true</tt> if this deque contained the specified element
695       */
696 <    public boolean remove(Object e) {
697 <        return removeFirstOccurrence(e);
696 >    public boolean remove(Object o) {
697 >        return removeFirstOccurrence(o);
698      }
699  
700      /**
701       * Removes all of the elements from this deque.
702 +     * The deque will be empty after this call returns.
703       */
704      public void clear() {
705          int h = head;
# Line 666 | Line 711 | public class ArrayDeque<E> extends Abstr
711              do {
712                  elements[i] = null;
713                  i = (i + 1) & mask;
714 <            } while(i != t);
714 >            } while (i != t);
715          }
716      }
717  
718      /**
719 <     * Returns an array containing all of the elements in this list
720 <     * in the correct order.
719 >     * Returns an array containing all of the elements in this deque
720 >     * in proper sequence (from first to last element).
721 >     *
722 >     * <p>The returned array will be "safe" in that no references to it are
723 >     * maintained by this deque.  (In other words, this method must allocate
724 >     * a new array).  The caller is thus free to modify the returned array.
725 >     *
726 >     * <p>This method acts as bridge between array-based and collection-based
727 >     * APIs.
728       *
729 <     * @return an array containing all of the elements in this list
678 <     *         in the correct order
729 >     * @return an array containing all of the elements in this deque
730       */
731      public Object[] toArray() {
732 <        return copyElements(new Object[size()]);
732 >        return copyElements(new Object[size()]);
733      }
734  
735      /**
736 <     * Returns an array containing all of the elements in this deque in the
737 <     * correct order; the runtime type of the returned array is that of the
738 <     * specified array.  If the deque fits in the specified array, it is
739 <     * returned therein.  Otherwise, a new array is allocated with the runtime
740 <     * type of the specified array and the size of this deque.
736 >     * Returns an array containing all of the elements in this deque in
737 >     * proper sequence (from first to last element); the runtime type of the
738 >     * returned array is that of the specified array.  If the deque fits in
739 >     * the specified array, it is returned therein.  Otherwise, a new array
740 >     * is allocated with the runtime type of the specified array and the
741 >     * size of this deque.
742       *
743 <     * <p>If the deque fits in the specified array with room to spare (i.e.,
744 <     * the array has more elements than the deque), the element in the array
745 <     * immediately following the end of the collection is set to <tt>null</tt>.
743 >     * <p>If this deque fits in the specified array with room to spare
744 >     * (i.e., the array has more elements than this deque), the element in
745 >     * the array immediately following the end of the deque is set to
746 >     * <tt>null</tt>.
747 >     *
748 >     * <p>Like the {@link #toArray()} method, this method acts as bridge between
749 >     * array-based and collection-based APIs.  Further, this method allows
750 >     * precise control over the runtime type of the output array, and may,
751 >     * under certain circumstances, be used to save allocation costs.
752 >     *
753 >     * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
754 >     * The following code can be used to dump the deque into a newly
755 >     * allocated array of <tt>String</tt>:
756 >     *
757 >     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
758 >     *
759 >     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
760 >     * <tt>toArray()</tt>.
761       *
762       * @param a the array into which the elements of the deque are to
763 <     *          be stored, if it is big enough; otherwise, a new array of the
764 <     *          same runtime type is allocated for this purpose
765 <     * @return an array containing the elements of the deque
766 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
767 <     *         of the runtime type of every element in this deque
763 >     *          be stored, if it is big enough; otherwise, a new array of the
764 >     *          same runtime type is allocated for this purpose
765 >     * @return an array containing all of the elements in this deque
766 >     * @throws ArrayStoreException if the runtime type of the specified array
767 >     *         is not a supertype of the runtime type of every element in
768 >     *         this deque
769 >     * @throws NullPointerException if the specified array is null
770       */
771 +    @SuppressWarnings("unchecked")
772      public <T> T[] toArray(T[] a) {
773          int size = size();
774          if (a.length < size)
775              a = (T[])java.lang.reflect.Array.newInstance(
776                      a.getClass().getComponentType(), size);
777 <        copyElements(a);
777 >        copyElements(a);
778          if (a.length > size)
779              a[size] = null;
780          return a;
# Line 718 | Line 788 | public class ArrayDeque<E> extends Abstr
788       * @return a copy of this deque
789       */
790      public ArrayDeque<E> clone() {
791 <        try {
791 >        try {
792 >            @SuppressWarnings("unchecked")
793              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
794 <            // 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);
794 >            result.elements = Arrays.copyOf(elements, elements.length);
795              return result;
796  
797 <        } catch (CloneNotSupportedException e) {
797 >        } catch (CloneNotSupportedException e) {
798              throw new AssertionError();
799          }
800      }
# Line 742 | Line 811 | public class ArrayDeque<E> extends Abstr
811       * followed by all of its elements (each an object reference) in
812       * first-to-last order.
813       */
814 <    private void writeObject(ObjectOutputStream s) throws IOException {
814 >    private void writeObject(java.io.ObjectOutputStream s)
815 >            throws java.io.IOException {
816          s.defaultWriteObject();
817  
818          // Write out size
819 <        int size = size();
750 <        s.writeInt(size);
819 >        s.writeInt(size());
820  
821          // Write out elements in order.
753        int i = head;
822          int mask = elements.length - 1;
823 <        for (int j = 0; j < size; j++) {
823 >        for (int i = head; i != tail; i = (i + 1) & mask)
824              s.writeObject(elements[i]);
757            i = (i + 1) & mask;
758        }
825      }
826  
827      /**
828       * Deserialize this deque.
829       */
830 <    private void readObject(ObjectInputStream s)
831 <            throws IOException, ClassNotFoundException {
830 >    private void readObject(java.io.ObjectInputStream s)
831 >            throws java.io.IOException, ClassNotFoundException {
832          s.defaultReadObject();
833  
834          // Read in size and allocate array
# Line 773 | Line 839 | public class ArrayDeque<E> extends Abstr
839  
840          // Read in all elements in the proper order.
841          for (int i = 0; i < size; i++)
842 <            elements[i] = (E)s.readObject();
777 <
842 >            elements[i] = s.readObject();
843      }
844   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines