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.35 by jsr166, Fri Dec 2 15:47:22 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 >    @SuppressWarnings("unchecked")
305 >    public E peekFirst() {
306 >        // elements[head] is null if deque empty
307 >        return (E) elements[head];
308 >    }
309 >
310 >    @SuppressWarnings("unchecked")
311 >    public E peekLast() {
312 >        return (E) elements[(tail - 1) & (elements.length - 1)];
313      }
314  
315      /**
316       * Removes the first occurrence of the specified element in this
317 <     * deque (when traversing the deque from head to tail).  If the deque
318 <     * does not contain the element, it is unchanged.
317 >     * deque (when traversing the deque from head to tail).
318 >     * If the deque does not contain the element, it is unchanged.
319 >     * More formally, removes the first element <tt>e</tt> such that
320 >     * <tt>o.equals(e)</tt> (if such an element exists).
321 >     * Returns <tt>true</tt> if this deque contained the specified element
322 >     * (or equivalently, if this deque changed as a result of the call).
323       *
324 <     * @param e element to be removed from this deque, if present
324 >     * @param o element to be removed from this deque, if present
325       * @return <tt>true</tt> if the deque contained the specified element
326       */
327 <    public boolean removeFirstOccurrence(Object e) {
328 <        if (e == null)
327 >    public boolean removeFirstOccurrence(Object o) {
328 >        if (o == null)
329              return false;
330          int mask = elements.length - 1;
331          int i = head;
332 <        E x;
332 >        Object x;
333          while ( (x = elements[i]) != null) {
334 <            if (e.equals(x)) {
334 >            if (o.equals(x)) {
335                  delete(i);
336                  return true;
337              }
# Line 379 | Line 342 | public class ArrayDeque<E> extends Abstr
342  
343      /**
344       * Removes the last occurrence of the specified element in this
345 <     * deque (when traversing the deque from head to tail).  If the deque
346 <     * does not contain the element, it is unchanged.
345 >     * deque (when traversing the deque from head to tail).
346 >     * If the deque does not contain the element, it is unchanged.
347 >     * More formally, removes the last element <tt>e</tt> such that
348 >     * <tt>o.equals(e)</tt> (if such an element exists).
349 >     * Returns <tt>true</tt> if this deque contained the specified element
350 >     * (or equivalently, if this deque changed as a result of the call).
351       *
352 <     * @param e element to be removed from this deque, if present
352 >     * @param o element to be removed from this deque, if present
353       * @return <tt>true</tt> if the deque contained the specified element
354       */
355 <    public boolean removeLastOccurrence(Object e) {
356 <        if (e == null)
355 >    public boolean removeLastOccurrence(Object o) {
356 >        if (o == null)
357              return false;
358          int mask = elements.length - 1;
359          int i = (tail - 1) & mask;
360 <        E x;
360 >        Object x;
361          while ( (x = elements[i]) != null) {
362 <            if (e.equals(x)) {
362 >            if (o.equals(x)) {
363                  delete(i);
364                  return true;
365              }
# Line 404 | Line 371 | public class ArrayDeque<E> extends Abstr
371      // *** Queue methods ***
372  
373      /**
374 <     * 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.
374 >     * Inserts the specified element at the end of this deque.
375       *
376       * <p>This method is equivalent to {@link #addLast}.
377       *
378 <     * @param e the element to insert
379 <     * @return <tt>true</tt> (as per the spec for {@link Collection#add})
380 <     * @throws NullPointerException if <tt>e</tt> is null
378 >     * @param e the element to add
379 >     * @return <tt>true</tt> (as specified by {@link Collection#add})
380 >     * @throws NullPointerException if the specified element is null
381       */
382      public boolean add(E e) {
383          addLast(e);
# Line 431 | Line 385 | public class ArrayDeque<E> extends Abstr
385      }
386  
387      /**
388 <     * 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.
388 >     * Inserts the specified element at the end of this deque.
389       *
390 <     * <p>This method is equivalent to {@link #pollFirst}.
390 >     * <p>This method is equivalent to {@link #offerLast}.
391       *
392 <     * @return the first element of this deque, or <tt>null</tt> if
393 <     *     this deque is empty
392 >     * @param e the element to add
393 >     * @return <tt>true</tt> (as specified by {@link Queue#offer})
394 >     * @throws NullPointerException if the specified element is null
395       */
396 <    public E poll() {
397 <        return pollFirst();
396 >    public boolean offer(E e) {
397 >        return offerLast(e);
398      }
399  
400      /**
401       * Retrieves and removes the head of the queue represented by this deque.
402 <     * This method differs from the <tt>poll</tt> method in that it throws an
402 >     *
403 >     * This method differs from {@link #poll poll} only in that it throws an
404       * exception if this deque is empty.
405       *
406       * <p>This method is equivalent to {@link #removeFirst}.
407       *
408       * @return the head of the queue represented by this deque
409 <     * @throws NoSuchElementException if this deque is empty
409 >     * @throws NoSuchElementException {@inheritDoc}
410       */
411      public E remove() {
412          return removeFirst();
413      }
414  
415      /**
416 <     * Retrieves, but does not remove, the head of the queue represented by
417 <     * this deque, returning <tt>null</tt> if this deque is empty.
416 >     * Retrieves and removes the head of the queue represented by this deque
417 >     * (in other words, the first element of this deque), or returns
418 >     * <tt>null</tt> if this deque is empty.
419       *
420 <     * <p>This method is equivalent to {@link #peekFirst}
420 >     * <p>This method is equivalent to {@link #pollFirst}.
421       *
422       * @return the head of the queue represented by this deque, or
423 <     *     <tt>null</tt> if this deque is empty
423 >     *         <tt>null</tt> if this deque is empty
424       */
425 <    public E peek() {
426 <        return peekFirst();
425 >    public E poll() {
426 >        return pollFirst();
427      }
428  
429      /**
430       * Retrieves, but does not remove, the head of the queue represented by
431 <     * this deque.  This method differs from the <tt>peek</tt> method only in
431 >     * this deque.  This method differs from {@link #peek peek} only in
432       * that it throws an exception if this deque is empty.
433       *
434 <     * <p>This method is equivalent to {@link #getFirst}
434 >     * <p>This method is equivalent to {@link #getFirst}.
435       *
436       * @return the head of the queue represented by this deque
437 <     * @throws NoSuchElementException if this deque is empty
437 >     * @throws NoSuchElementException {@inheritDoc}
438       */
439      public E element() {
440          return getFirst();
441      }
442  
443 +    /**
444 +     * Retrieves, but does not remove, the head of the queue represented by
445 +     * this deque, or returns <tt>null</tt> if this deque is empty.
446 +     *
447 +     * <p>This method is equivalent to {@link #peekFirst}.
448 +     *
449 +     * @return the head of the queue represented by this deque, or
450 +     *         <tt>null</tt> if this deque is empty
451 +     */
452 +    public E peek() {
453 +        return peekFirst();
454 +    }
455 +
456      // *** Stack methods ***
457  
458      /**
459       * Pushes an element onto the stack represented by this deque.  In other
460 <     * words, inserts the element to the front this deque.
460 >     * words, inserts the element at the front of this deque.
461       *
462       * <p>This method is equivalent to {@link #addFirst}.
463       *
464       * @param e the element to push
465 <     * @throws NullPointerException if <tt>e</tt> is null
465 >     * @throws NullPointerException if the specified element is null
466       */
467      public void push(E e) {
468          addFirst(e);
# Line 508 | Line 475 | public class ArrayDeque<E> extends Abstr
475       * <p>This method is equivalent to {@link #removeFirst()}.
476       *
477       * @return the element at the front of this deque (which is the top
478 <     *     of the stack represented by this deque)
479 <     * @throws NoSuchElementException if this deque is empty
478 >     *         of the stack represented by this deque)
479 >     * @throws NoSuchElementException {@inheritDoc}
480       */
481      public E pop() {
482          return removeFirst();
483      }
484  
485 +    private void checkInvariants() {
486 +        assert elements[tail] == null;
487 +        assert head == tail ? elements[head] == null :
488 +            (elements[head] != null &&
489 +             elements[(tail - 1) & (elements.length - 1)] != null);
490 +        assert elements[(head - 1) & (elements.length - 1)] == null;
491 +    }
492 +
493      /**
494 <     * Remove the element at the specified position in the elements array,
495 <     * adjusting head, tail, and size as necessary.  This can result in
496 <     * motion of elements backwards or forwards in the array.
497 <     *
498 <     * <p>This method is called delete rather than remove to emphasize the
499 <     * that its semantics differ from those of List.remove(int).
500 <     *
494 >     * Removes the element at the specified position in the elements array,
495 >     * adjusting head and tail as necessary.  This can result in motion of
496 >     * elements backwards or forwards in the array.
497 >     *
498 >     * <p>This method is called delete rather than remove to emphasize
499 >     * that its semantics differ from those of {@link List#remove(int)}.
500 >     *
501       * @return true if elements moved backwards
502       */
503      private boolean delete(int i) {
504 <        // Case 1: Deque doesn't wrap
505 <        // Case 2: Deque does wrap and removed element is in the head portion
506 <        if ((head < tail || tail == 0) || i >= head) {
507 <            System.arraycopy(elements, head, elements, head + 1, i - head);
508 <            elements[head] = null;
509 <            head = (head + 1) & (elements.length - 1);
504 >        checkInvariants();
505 >        final Object[] elements = this.elements;
506 >        final int mask = elements.length - 1;
507 >        final int h = head;
508 >        final int t = tail;
509 >        final int front = (i - h) & mask;
510 >        final int back  = (t - i) & mask;
511 >
512 >        // Invariant: head <= i < tail mod circularity
513 >        if (front >= ((t - h) & mask))
514 >            throw new ConcurrentModificationException();
515 >
516 >        // Optimize for least element motion
517 >        if (front < back) {
518 >            if (h <= i) {
519 >                System.arraycopy(elements, h, elements, h + 1, front);
520 >            } else { // Wrap around
521 >                System.arraycopy(elements, 0, elements, 1, i);
522 >                elements[0] = elements[mask];
523 >                System.arraycopy(elements, h, elements, h + 1, mask - h);
524 >            }
525 >            elements[h] = null;
526 >            head = (h + 1) & mask;
527              return false;
528 +        } else {
529 +            if (i < t) { // Copy the null tail as well
530 +                System.arraycopy(elements, i + 1, elements, i, back);
531 +                tail = t - 1;
532 +            } else { // Wrap around
533 +                System.arraycopy(elements, i + 1, elements, i, mask - i);
534 +                elements[mask] = elements[0];
535 +                System.arraycopy(elements, 1, elements, 0, t);
536 +                tail = (t - 1) & mask;
537 +            }
538 +            return true;
539          }
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;
540      }
541  
542      // *** Collection Methods ***
# Line 554 | Line 551 | public class ArrayDeque<E> extends Abstr
551      }
552  
553      /**
554 <     * Returns <tt>true</tt> if this collection contains no elements.<p>
554 >     * Returns <tt>true</tt> if this deque contains no elements.
555       *
556 <     * @return <tt>true</tt> if this collection contains no elements.
556 >     * @return <tt>true</tt> if this deque contains no elements
557       */
558      public boolean isEmpty() {
559          return head == tail;
# Line 567 | Line 564 | public class ArrayDeque<E> extends Abstr
564       * will be ordered from first (head) to last (tail).  This is the same
565       * order that elements would be dequeued (via successive calls to
566       * {@link #remove} or popped (via successive calls to {@link #pop}).
567 <     *
568 <     * @return an <tt>Iterator</tt> over the elements in this deque
567 >     *
568 >     * @return an iterator over the elements in this deque
569       */
570      public Iterator<E> iterator() {
571          return new DeqIterator();
572      }
573  
574 +    public Iterator<E> descendingIterator() {
575 +        return new DescendingIterator();
576 +    }
577 +
578      private class DeqIterator implements Iterator<E> {
579          /**
580           * Index of element to be returned by subsequent call to next.
# Line 597 | Line 598 | public class ArrayDeque<E> extends Abstr
598          }
599  
600          public E next() {
600            E result;
601              if (cursor == fence)
602                  throw new NoSuchElementException();
603 +            @SuppressWarnings("unchecked") E result = (E) elements[cursor];
604              // This check doesn't catch all possible comodifications,
605              // but does catch the ones that corrupt traversal
606 <            if (tail != fence || (result = elements[cursor]) == null)
606 >            if (tail != fence || result == null)
607                  throw new ConcurrentModificationException();
608              lastRet = cursor;
609              cursor = (cursor + 1) & (elements.length - 1);
# Line 612 | Line 613 | public class ArrayDeque<E> extends Abstr
613          public void remove() {
614              if (lastRet < 0)
615                  throw new IllegalStateException();
616 <            if (delete(lastRet))
617 <                cursor--;
616 >            if (delete(lastRet)) { // if left-shifted, undo increment in next()
617 >                cursor = (cursor - 1) & (elements.length - 1);
618 >                fence = tail;
619 >            }
620 >            lastRet = -1;
621 >        }
622 >    }
623 >
624 >    private class DescendingIterator implements Iterator<E> {
625 >        /*
626 >         * This class is nearly a mirror-image of DeqIterator, using
627 >         * tail instead of head for initial cursor, and head instead of
628 >         * tail for fence.
629 >         */
630 >        private int cursor = tail;
631 >        private int fence = head;
632 >        private int lastRet = -1;
633 >
634 >        public boolean hasNext() {
635 >            return cursor != fence;
636 >        }
637 >
638 >        public E next() {
639 >            if (cursor == fence)
640 >                throw new NoSuchElementException();
641 >            cursor = (cursor - 1) & (elements.length - 1);
642 >            @SuppressWarnings("unchecked") E result = (E) elements[cursor];
643 >            if (head != fence || result == null)
644 >                throw new ConcurrentModificationException();
645 >            lastRet = cursor;
646 >            return result;
647 >        }
648 >
649 >        public void remove() {
650 >            if (lastRet < 0)
651 >                throw new IllegalStateException();
652 >            if (!delete(lastRet)) {
653 >                cursor = (cursor + 1) & (elements.length - 1);
654 >                fence = head;
655 >            }
656              lastRet = -1;
618            fence = tail;
657          }
658      }
659  
660      /**
661 <     * Returns <tt>true</tt> if this deque contains the specified
662 <     * element.  More formally, returns <tt>true</tt> if and only if this
663 <     * deque contains at least one element <tt>e</tt> such that
626 <     * <tt>e.equals(o)</tt>.
661 >     * Returns <tt>true</tt> if this deque contains the specified element.
662 >     * More formally, returns <tt>true</tt> if and only if this deque contains
663 >     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
664       *
665       * @param o object to be checked for containment in this deque
666       * @return <tt>true</tt> if this deque contains the specified element
# Line 633 | Line 670 | public class ArrayDeque<E> extends Abstr
670              return false;
671          int mask = elements.length - 1;
672          int i = head;
673 <        E x;
673 >        Object x;
674          while ( (x = elements[i]) != null) {
675              if (o.equals(x))
676                  return true;
# Line 644 | Line 681 | public class ArrayDeque<E> extends Abstr
681  
682      /**
683       * Removes a single instance of the specified element from this deque.
684 <     * This method is equivalent to {@link #removeFirstOccurrence}.
684 >     * If the deque does not contain the element, it is unchanged.
685 >     * More formally, removes the first element <tt>e</tt> such that
686 >     * <tt>o.equals(e)</tt> (if such an element exists).
687 >     * Returns <tt>true</tt> if this deque contained the specified element
688 >     * (or equivalently, if this deque changed as a result of the call).
689 >     *
690 >     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
691       *
692 <     * @param e element to be removed from this deque, if present
692 >     * @param o element to be removed from this deque, if present
693       * @return <tt>true</tt> if this deque contained the specified element
694       */
695 <    public boolean remove(Object e) {
696 <        return removeFirstOccurrence(e);
695 >    public boolean remove(Object o) {
696 >        return removeFirstOccurrence(o);
697      }
698  
699      /**
700       * Removes all of the elements from this deque.
701 +     * The deque will be empty after this call returns.
702       */
703      public void clear() {
704          int h = head;
# Line 666 | Line 710 | public class ArrayDeque<E> extends Abstr
710              do {
711                  elements[i] = null;
712                  i = (i + 1) & mask;
713 <            } while(i != t);
713 >            } while (i != t);
714          }
715      }
716  
717      /**
718 <     * Returns an array containing all of the elements in this list
719 <     * in the correct order.
718 >     * Returns an array containing all of the elements in this deque
719 >     * in proper sequence (from first to last element).
720 >     *
721 >     * <p>The returned array will be "safe" in that no references to it are
722 >     * maintained by this deque.  (In other words, this method must allocate
723 >     * a new array).  The caller is thus free to modify the returned array.
724 >     *
725 >     * <p>This method acts as bridge between array-based and collection-based
726 >     * APIs.
727       *
728 <     * @return an array containing all of the elements in this list
678 <     *         in the correct order
728 >     * @return an array containing all of the elements in this deque
729       */
730      public Object[] toArray() {
731 <        return copyElements(new Object[size()]);
731 >        return copyElements(new Object[size()]);
732      }
733  
734      /**
735 <     * Returns an array containing all of the elements in this deque in the
736 <     * correct order; the runtime type of the returned array is that of the
737 <     * specified array.  If the deque fits in the specified array, it is
738 <     * returned therein.  Otherwise, a new array is allocated with the runtime
739 <     * type of the specified array and the size of this deque.
735 >     * Returns an array containing all of the elements in this deque in
736 >     * proper sequence (from first to last element); the runtime type of the
737 >     * returned array is that of the specified array.  If the deque fits in
738 >     * the specified array, it is returned therein.  Otherwise, a new array
739 >     * is allocated with the runtime type of the specified array and the
740 >     * size of this deque.
741       *
742 <     * <p>If the deque fits in the specified array with room to spare (i.e.,
743 <     * the array has more elements than the deque), the element in the array
744 <     * immediately following the end of the collection is set to <tt>null</tt>.
742 >     * <p>If this deque fits in the specified array with room to spare
743 >     * (i.e., the array has more elements than this deque), the element in
744 >     * the array immediately following the end of the deque is set to
745 >     * <tt>null</tt>.
746 >     *
747 >     * <p>Like the {@link #toArray()} method, this method acts as bridge between
748 >     * array-based and collection-based APIs.  Further, this method allows
749 >     * precise control over the runtime type of the output array, and may,
750 >     * under certain circumstances, be used to save allocation costs.
751 >     *
752 >     * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
753 >     * The following code can be used to dump the deque into a newly
754 >     * allocated array of <tt>String</tt>:
755 >     *
756 >     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
757 >     *
758 >     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
759 >     * <tt>toArray()</tt>.
760       *
761       * @param a the array into which the elements of the deque are to
762 <     *          be stored, if it is big enough; otherwise, a new array of the
763 <     *          same runtime type is allocated for this purpose
764 <     * @return an array containing the elements of the deque
765 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
766 <     *         of the runtime type of every element in this deque
762 >     *          be stored, if it is big enough; otherwise, a new array of the
763 >     *          same runtime type is allocated for this purpose
764 >     * @return an array containing all of the elements in this deque
765 >     * @throws ArrayStoreException if the runtime type of the specified array
766 >     *         is not a supertype of the runtime type of every element in
767 >     *         this deque
768 >     * @throws NullPointerException if the specified array is null
769       */
770 +    @SuppressWarnings("unchecked")
771      public <T> T[] toArray(T[] a) {
772          int size = size();
773          if (a.length < size)
774              a = (T[])java.lang.reflect.Array.newInstance(
775                      a.getClass().getComponentType(), size);
776 <        copyElements(a);
776 >        copyElements(a);
777          if (a.length > size)
778              a[size] = null;
779          return a;
# Line 718 | Line 787 | public class ArrayDeque<E> extends Abstr
787       * @return a copy of this deque
788       */
789      public ArrayDeque<E> clone() {
790 <        try {
790 >        try {
791 >            @SuppressWarnings("unchecked")
792              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
793 <            // 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);
793 >            result.elements = Arrays.copyOf(elements, elements.length);
794              return result;
795  
796 <        } catch (CloneNotSupportedException e) {
796 >        } catch (CloneNotSupportedException e) {
797              throw new AssertionError();
798          }
799      }
# Line 742 | Line 810 | public class ArrayDeque<E> extends Abstr
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.
828       */
829 <    private void readObject(ObjectInputStream s)
830 <            throws IOException, ClassNotFoundException {
829 >    private void readObject(java.io.ObjectInputStream s)
830 >            throws java.io.IOException, ClassNotFoundException {
831          s.defaultReadObject();
832  
833          // Read in size and allocate array
# Line 773 | Line 838 | public class ArrayDeque<E> extends Abstr
838  
839          // Read in all elements in the proper order.
840          for (int i = 0; i < size; i++)
841 <            elements[i] = (E)s.readObject();
777 <
841 >            elements[i] = s.readObject();
842      }
843   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines