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.4 by dl, Tue Mar 8 19:07:39 2005 UTC vs.
Revision 1.30 by jsr166, Sun May 18 23:47:55 2008 UTC

# Line 18 | Line 18 | import java.io.*;
18   * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
19   * Exceptions include {@link #remove(Object) remove}, {@link
20   * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
21 < * removeLastOccurrence}, {@link #contains contains }, {@link #iterator
21 > * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
22   * iterator.remove()}, and the bulk operations, all of which run in linear
23   * time.
24   *
25   * <p>The iterators returned by this class's <tt>iterator</tt> method are
26   * <i>fail-fast</i>: If the deque is modified at any time after the iterator
27 < * is created, in any way except through the iterator's own remove method, the
28 < * iterator will generally throw a {@link ConcurrentModificationException}.
29 < * Thus, in the face of concurrent modification, the iterator fails quickly
30 < * and cleanly, rather than risking arbitrary, non-deterministic behavior at
31 < * an undetermined time in the future.
27 > * is created, in any way except through the iterator's own <tt>remove</tt>
28 > * method, the iterator will generally throw a {@link
29 > * ConcurrentModificationException}.  Thus, in the face of concurrent
30 > * modification, the iterator fails quickly and cleanly, rather than risking
31 > * arbitrary, non-deterministic behavior at an undetermined time in the
32 > * future.
33   *
34   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
35   * as it is, generally speaking, impossible to make any hard guarantees in the
36   * presence of unsynchronized concurrent modification.  Fail-fast iterators
37 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
37 > * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
38   * Therefore, it would be wrong to write a program that depended on this
39   * exception for its correctness: <i>the fail-fast behavior of iterators
40   * should be used only to detect bugs.</i>
41   *
42   * <p>This class and its iterator implement all of the
43 < * optional methods of the {@link Collection} and {@link
44 < * Iterator} interfaces.  This class is a member of the <a
45 < * href="{@docRoot}/../guide/collections/index.html"> Java Collections
46 < * Framework</a>.
43 > * <em>optional</em> methods of the {@link Collection} and {@link
44 > * Iterator} interfaces.
45 > *
46 > * <p>This class is a member of the
47 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
48 > * Java Collections Framework</a>.
49   *
50   * @author  Josh Bloch and Doug Lea
51   * @since   1.6
# Line 87 | Line 90 | public class ArrayDeque<E> extends Abstr
90      /**
91       * Allocate empty array to hold the given number of elements.
92       *
93 <     * @param numElements  the number of elements to hold.
93 >     * @param numElements  the number of elements to hold
94       */
95 <    private void allocateElements(int numElements) {  
95 >    private void allocateElements(int numElements) {
96          int initialCapacity = MIN_INITIAL_CAPACITY;
97          // Find the best power of two to hold elements.
98          // Tests "<=" because arrays aren't kept full.
# Line 113 | Line 116 | public class ArrayDeque<E> extends Abstr
116       * when head and tail have wrapped around to become equal.
117       */
118      private void doubleCapacity() {
119 <        assert head == tail;
119 >        assert head == tail;
120          int p = head;
121          int n = elements.length;
122          int r = n - p; // number of elements to the right of p
# Line 129 | Line 132 | public class ArrayDeque<E> extends Abstr
132      }
133  
134      /**
135 <     * Copy the elements from our element array into the specified array,
135 >     * Copies the elements from our element array into the specified array,
136       * in order (from first to last element in the deque).  It is assumed
137       * that the array is large enough to hold all elements in the deque.
138       *
# Line 184 | Line 187 | public class ArrayDeque<E> extends Abstr
187      // terms of these.
188  
189      /**
190 <     * Inserts the specified element to the front this deque.
190 >     * Inserts the specified element at the front of this deque.
191       *
192 <     * @param e the element to insert
193 <     * @throws NullPointerException if <tt>e</tt> is null
192 >     * @param e the element to add
193 >     * @throws NullPointerException if the specified element is null
194       */
195      public void addFirst(E e) {
196          if (e == null)
197              throw new NullPointerException();
198          elements[head = (head - 1) & (elements.length - 1)] = e;
199 <        if (head == tail)
199 >        if (head == tail)
200              doubleCapacity();
201      }
202  
203      /**
204 <     * Inserts the specified element to the end this deque.
205 <     * This method is equivalent to {@link Collection#add} and
206 <     * {@link #push}.
204 >     * Inserts the specified element at the end of this deque.
205 >     *
206 >     * <p>This method is equivalent to {@link #add}.
207       *
208 <     * @param e the element to insert
209 <     * @throws NullPointerException if <tt>e</tt> is null
208 >     * @param e the element to add
209 >     * @throws NullPointerException if the specified element is null
210       */
211      public void addLast(E e) {
212          if (e == null)
# Line 214 | Line 217 | public class ArrayDeque<E> extends Abstr
217      }
218  
219      /**
220 <     * 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.
220 >     * Inserts the specified element at the front of this deque.
221       *
222 <     * @param e the element to insert
223 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerFirst})
224 <     * @throws NullPointerException if <tt>e</tt> is null
222 >     * @param e the element to add
223 >     * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
224 >     * @throws NullPointerException if the specified element is null
225       */
226      public boolean offerFirst(E e) {
227          addFirst(e);
# Line 260 | Line 229 | public class ArrayDeque<E> extends Abstr
229      }
230  
231      /**
232 <     * Inserts the specified element to the end this deque.
232 >     * Inserts the specified element at the end of this deque.
233       *
234 <     * @param e the element to insert
235 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerLast})
236 <     * @throws NullPointerException if <tt>e</tt> is null
234 >     * @param e the element to add
235 >     * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
236 >     * @throws NullPointerException if the specified element is null
237       */
238      public boolean offerLast(E e) {
239          addLast(e);
# Line 272 | Line 241 | public class ArrayDeque<E> extends Abstr
241      }
242  
243      /**
244 <     * 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
244 >     * @throws NoSuchElementException {@inheritDoc}
245       */
246      public E removeFirst() {
247          E x = pollFirst();
# Line 287 | Line 251 | public class ArrayDeque<E> extends Abstr
251      }
252  
253      /**
254 <     * 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
254 >     * @throws NoSuchElementException {@inheritDoc}
255       */
256      public E removeLast() {
257          E x = pollLast();
# Line 301 | Line 260 | public class ArrayDeque<E> extends Abstr
260          return x;
261      }
262  
263 <    /**
264 <     * Retrieves, but does not remove, the first element of this deque,
265 <     * returning <tt>null</tt> if this deque is empty.
266 <     *
267 <     * @return the first element of this deque, or <tt>null</tt> if
268 <     *     this deque is empty
269 <     */
270 <    public E peekFirst() {
312 <        return elements[head]; // elements[head] is null if deque empty
263 >    public E pollFirst() {
264 >        int h = head;
265 >        E result = elements[h]; // 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 >        E result = 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];
# Line 339 | Line 291 | public class ArrayDeque<E> extends Abstr
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)];
# Line 353 | Line 300 | public class ArrayDeque<E> extends Abstr
300          return x;
301      }
302  
303 +    public E peekFirst() {
304 +        return elements[head]; // elements[head] is null if deque empty
305 +    }
306 +
307 +    public E peekLast() {
308 +        return elements[(tail - 1) & (elements.length - 1)];
309 +    }
310 +
311      /**
312       * Removes the first occurrence of the specified element in this
313 <     * deque (when traversing the deque from head to tail).  If the deque
314 <     * does not contain the element, it is unchanged.
313 >     * deque (when traversing the deque from head to tail).
314 >     * If the deque does not contain the element, it is unchanged.
315 >     * More formally, removes the first element <tt>e</tt> such that
316 >     * <tt>o.equals(e)</tt> (if such an element exists).
317 >     * Returns <tt>true</tt> if this deque contained the specified element
318 >     * (or equivalently, if this deque changed as a result of the call).
319       *
320 <     * @param e element to be removed from this deque, if present
320 >     * @param o element to be removed from this deque, if present
321       * @return <tt>true</tt> if the deque contained the specified element
322       */
323 <    public boolean removeFirstOccurrence(Object e) {
324 <        if (e == null)
323 >    public boolean removeFirstOccurrence(Object o) {
324 >        if (o == null)
325              return false;
326          int mask = elements.length - 1;
327          int i = head;
328          E x;
329          while ( (x = elements[i]) != null) {
330 <            if (e.equals(x)) {
330 >            if (o.equals(x)) {
331                  delete(i);
332                  return true;
333              }
# Line 379 | Line 338 | public class ArrayDeque<E> extends Abstr
338  
339      /**
340       * Removes the last occurrence of the specified element in this
341 <     * deque (when traversing the deque from head to tail).  If the deque
342 <     * does not contain the element, it is unchanged.
341 >     * deque (when traversing the deque from head to tail).
342 >     * If the deque does not contain the element, it is unchanged.
343 >     * More formally, removes the last element <tt>e</tt> such that
344 >     * <tt>o.equals(e)</tt> (if such an element exists).
345 >     * Returns <tt>true</tt> if this deque contained the specified element
346 >     * (or equivalently, if this deque changed as a result of the call).
347       *
348 <     * @param e element to be removed from this deque, if present
348 >     * @param o element to be removed from this deque, if present
349       * @return <tt>true</tt> if the deque contained the specified element
350       */
351 <    public boolean removeLastOccurrence(Object e) {
352 <        if (e == null)
351 >    public boolean removeLastOccurrence(Object o) {
352 >        if (o == null)
353              return false;
354          int mask = elements.length - 1;
355          int i = (tail - 1) & mask;
356          E x;
357          while ( (x = elements[i]) != null) {
358 <            if (e.equals(x)) {
358 >            if (o.equals(x)) {
359                  delete(i);
360                  return true;
361              }
# Line 404 | Line 367 | public class ArrayDeque<E> extends Abstr
367      // *** Queue methods ***
368  
369      /**
370 <     * 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.
370 >     * Inserts the specified element at the end of this deque.
371       *
372       * <p>This method is equivalent to {@link #addLast}.
373       *
374 <     * @param e the element to insert
375 <     * @return <tt>true</tt> (as per the spec for {@link Collection#add})
376 <     * @throws NullPointerException if <tt>e</tt> is null
374 >     * @param e the element to add
375 >     * @return <tt>true</tt> (as specified by {@link Collection#add})
376 >     * @throws NullPointerException if the specified element is null
377       */
378      public boolean add(E e) {
379          addLast(e);
# Line 431 | Line 381 | public class ArrayDeque<E> extends Abstr
381      }
382  
383      /**
384 <     * 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.
384 >     * Inserts the specified element at the end of this deque.
385       *
386 <     * <p>This method is equivalent to {@link #pollFirst}.
386 >     * <p>This method is equivalent to {@link #offerLast}.
387       *
388 <     * @return the first element of this deque, or <tt>null</tt> if
389 <     *     this deque is empty
388 >     * @param e the element to add
389 >     * @return <tt>true</tt> (as specified by {@link Queue#offer})
390 >     * @throws NullPointerException if the specified element is null
391       */
392 <    public E poll() {
393 <        return pollFirst();
392 >    public boolean offer(E e) {
393 >        return offerLast(e);
394      }
395  
396      /**
397       * Retrieves and removes the head of the queue represented by this deque.
398 <     * This method differs from the <tt>poll</tt> method in that it throws an
398 >     *
399 >     * This method differs from {@link #poll poll} only in that it throws an
400       * exception if this deque is empty.
401       *
402       * <p>This method is equivalent to {@link #removeFirst}.
403       *
404       * @return the head of the queue represented by this deque
405 <     * @throws NoSuchElementException if this deque is empty
405 >     * @throws NoSuchElementException {@inheritDoc}
406       */
407      public E remove() {
408          return removeFirst();
409      }
410  
411      /**
412 <     * Retrieves, but does not remove, the head of the queue represented by
413 <     * this deque, returning <tt>null</tt> if this deque is empty.
412 >     * Retrieves and removes the head of the queue represented by this deque
413 >     * (in other words, the first element of this deque), or returns
414 >     * <tt>null</tt> if this deque is empty.
415       *
416 <     * <p>This method is equivalent to {@link #peekFirst}
416 >     * <p>This method is equivalent to {@link #pollFirst}.
417       *
418       * @return the head of the queue represented by this deque, or
419 <     *     <tt>null</tt> if this deque is empty
419 >     *         <tt>null</tt> if this deque is empty
420       */
421 <    public E peek() {
422 <        return peekFirst();
421 >    public E poll() {
422 >        return pollFirst();
423      }
424  
425      /**
426       * Retrieves, but does not remove, the head of the queue represented by
427 <     * this deque.  This method differs from the <tt>peek</tt> method only in
427 >     * this deque.  This method differs from {@link #peek peek} only in
428       * that it throws an exception if this deque is empty.
429       *
430 <     * <p>This method is equivalent to {@link #getFirst}
430 >     * <p>This method is equivalent to {@link #getFirst}.
431       *
432       * @return the head of the queue represented by this deque
433 <     * @throws NoSuchElementException if this deque is empty
433 >     * @throws NoSuchElementException {@inheritDoc}
434       */
435      public E element() {
436          return getFirst();
437      }
438  
439 +    /**
440 +     * Retrieves, but does not remove, the head of the queue represented by
441 +     * this deque, or returns <tt>null</tt> if this deque is empty.
442 +     *
443 +     * <p>This method is equivalent to {@link #peekFirst}.
444 +     *
445 +     * @return the head of the queue represented by this deque, or
446 +     *         <tt>null</tt> if this deque is empty
447 +     */
448 +    public E peek() {
449 +        return peekFirst();
450 +    }
451 +
452      // *** Stack methods ***
453  
454      /**
455       * Pushes an element onto the stack represented by this deque.  In other
456 <     * words, inserts the element to the front this deque.
456 >     * words, inserts the element at the front of this deque.
457       *
458       * <p>This method is equivalent to {@link #addFirst}.
459       *
460       * @param e the element to push
461 <     * @throws NullPointerException if <tt>e</tt> is null
461 >     * @throws NullPointerException if the specified element is null
462       */
463      public void push(E e) {
464          addFirst(e);
# Line 508 | Line 471 | public class ArrayDeque<E> extends Abstr
471       * <p>This method is equivalent to {@link #removeFirst()}.
472       *
473       * @return the element at the front of this deque (which is the top
474 <     *     of the stack represented by this deque)
475 <     * @throws NoSuchElementException if this deque is empty
474 >     *         of the stack represented by this deque)
475 >     * @throws NoSuchElementException {@inheritDoc}
476       */
477      public E pop() {
478          return removeFirst();
479      }
480  
481 +    private void checkInvariants() {
482 +        assert elements[tail] == null;
483 +        assert head == tail ? elements[head] == null :
484 +            (elements[head] != null &&
485 +             elements[(tail - 1) & (elements.length - 1)] != null);
486 +        assert elements[(head - 1) & (elements.length - 1)] == null;
487 +    }
488 +
489      /**
490 <     * Remove the element at the specified position in the elements array,
491 <     * adjusting head, tail, and size as necessary.  This can result in
492 <     * motion of elements backwards or forwards in the array.
493 <     *
494 <     * <p>This method is called delete rather than remove to emphasize
495 <     * that its semantics differ from those of List.remove(int).
496 <     *
490 >     * Removes the element at the specified position in the elements array,
491 >     * adjusting head and tail as necessary.  This can result in motion of
492 >     * elements backwards or forwards in the array.
493 >     *
494 >     * <p>This method is called delete rather than remove to emphasize
495 >     * that its semantics differ from those of {@link List#remove(int)}.
496 >     *
497       * @return true if elements moved backwards
498       */
499      private boolean delete(int i) {
500 <        // Case 1: Deque doesn't wrap
501 <        // Case 2: Deque does wrap and removed element is in the head portion
502 <        if ((head < tail || tail == 0) || i >= head) {
503 <            System.arraycopy(elements, head, elements, head + 1, i - head);
504 <            elements[head] = null;
505 <            head = (head + 1) & (elements.length - 1);
500 >        checkInvariants();
501 >        final E[] elements = this.elements;
502 >        final int mask = elements.length - 1;
503 >        final int h = head;
504 >        final int t = tail;
505 >        final int front = (i - h) & mask;
506 >        final int back  = (t - i) & mask;
507 >
508 >        // Invariant: head <= i < tail mod circularity
509 >        if (front >= ((t - h) & mask))
510 >            throw new ConcurrentModificationException();
511 >
512 >        // Optimize for least element motion
513 >        if (front < back) {
514 >            if (h <= i) {
515 >                System.arraycopy(elements, h, elements, h + 1, front);
516 >            } else { // Wrap around
517 >                System.arraycopy(elements, 0, elements, 1, i);
518 >                elements[0] = elements[mask];
519 >                System.arraycopy(elements, h, elements, h + 1, mask - h);
520 >            }
521 >            elements[h] = null;
522 >            head = (h + 1) & mask;
523              return false;
524 +        } else {
525 +            if (i < t) { // Copy the null tail as well
526 +                System.arraycopy(elements, i + 1, elements, i, back);
527 +                tail = t - 1;
528 +            } else { // Wrap around
529 +                System.arraycopy(elements, i + 1, elements, i, mask - i);
530 +                elements[mask] = elements[0];
531 +                System.arraycopy(elements, 1, elements, 0, t);
532 +                tail = (t - 1) & mask;
533 +            }
534 +            return true;
535          }
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;
536      }
537  
538      // *** Collection Methods ***
# Line 554 | Line 547 | public class ArrayDeque<E> extends Abstr
547      }
548  
549      /**
550 <     * Returns <tt>true</tt> if this collection contains no elements.<p>
550 >     * Returns <tt>true</tt> if this deque contains no elements.
551       *
552 <     * @return <tt>true</tt> if this collection contains no elements.
552 >     * @return <tt>true</tt> if this deque contains no elements
553       */
554      public boolean isEmpty() {
555          return head == tail;
# Line 567 | Line 560 | public class ArrayDeque<E> extends Abstr
560       * will be ordered from first (head) to last (tail).  This is the same
561       * order that elements would be dequeued (via successive calls to
562       * {@link #remove} or popped (via successive calls to {@link #pop}).
563 <     *
564 <     * @return an <tt>Iterator</tt> over the elements in this deque
563 >     *
564 >     * @return an iterator over the elements in this deque
565       */
566      public Iterator<E> iterator() {
567          return new DeqIterator();
568      }
569  
570 +    public Iterator<E> descendingIterator() {
571 +        return new DescendingIterator();
572 +    }
573 +
574      private class DeqIterator implements Iterator<E> {
575          /**
576           * Index of element to be returned by subsequent call to next.
# Line 597 | Line 594 | public class ArrayDeque<E> extends Abstr
594          }
595  
596          public E next() {
600            E result;
597              if (cursor == fence)
598                  throw new NoSuchElementException();
599 +            E result = elements[cursor];
600              // This check doesn't catch all possible comodifications,
601              // but does catch the ones that corrupt traversal
602 <            if (tail != fence || (result = elements[cursor]) == null)
602 >            if (tail != fence || result == null)
603                  throw new ConcurrentModificationException();
604              lastRet = cursor;
605              cursor = (cursor + 1) & (elements.length - 1);
# Line 612 | Line 609 | public class ArrayDeque<E> extends Abstr
609          public void remove() {
610              if (lastRet < 0)
611                  throw new IllegalStateException();
612 <            if (delete(lastRet))
613 <                cursor--;
612 >            if (delete(lastRet)) { // if left-shifted, undo increment in next()
613 >                cursor = (cursor - 1) & (elements.length - 1);
614 >                fence = tail;
615 >            }
616 >            lastRet = -1;
617 >        }
618 >    }
619 >
620 >    private class DescendingIterator implements Iterator<E> {
621 >        /*
622 >         * This class is nearly a mirror-image of DeqIterator, using
623 >         * tail instead of head for initial cursor, and head instead of
624 >         * tail for fence.
625 >         */
626 >        private int cursor = tail;
627 >        private int fence = head;
628 >        private int lastRet = -1;
629 >
630 >        public boolean hasNext() {
631 >            return cursor != fence;
632 >        }
633 >
634 >        public E next() {
635 >            if (cursor == fence)
636 >                throw new NoSuchElementException();
637 >            cursor = (cursor - 1) & (elements.length - 1);
638 >            E result = elements[cursor];
639 >            if (head != fence || result == null)
640 >                throw new ConcurrentModificationException();
641 >            lastRet = cursor;
642 >            return result;
643 >        }
644 >
645 >        public void remove() {
646 >            if (lastRet < 0)
647 >                throw new IllegalStateException();
648 >            if (!delete(lastRet)) {
649 >                cursor = (cursor + 1) & (elements.length - 1);
650 >                fence = head;
651 >            }
652              lastRet = -1;
618            fence = tail;
653          }
654      }
655  
656      /**
657 <     * Returns <tt>true</tt> if this deque contains the specified
658 <     * element.  More formally, returns <tt>true</tt> if and only if this
659 <     * deque contains at least one element <tt>e</tt> such that
626 <     * <tt>e.equals(o)</tt>.
657 >     * Returns <tt>true</tt> if this deque contains the specified element.
658 >     * More formally, returns <tt>true</tt> if and only if this deque contains
659 >     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
660       *
661       * @param o object to be checked for containment in this deque
662       * @return <tt>true</tt> if this deque contains the specified element
# Line 644 | Line 677 | public class ArrayDeque<E> extends Abstr
677  
678      /**
679       * Removes a single instance of the specified element from this deque.
680 <     * This method is equivalent to {@link #removeFirstOccurrence}.
680 >     * If the deque does not contain the element, it is unchanged.
681 >     * More formally, removes the first element <tt>e</tt> such that
682 >     * <tt>o.equals(e)</tt> (if such an element exists).
683 >     * Returns <tt>true</tt> if this deque contained the specified element
684 >     * (or equivalently, if this deque changed as a result of the call).
685 >     *
686 >     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
687       *
688 <     * @param e element to be removed from this deque, if present
688 >     * @param o element to be removed from this deque, if present
689       * @return <tt>true</tt> if this deque contained the specified element
690       */
691 <    public boolean remove(Object e) {
692 <        return removeFirstOccurrence(e);
691 >    public boolean remove(Object o) {
692 >        return removeFirstOccurrence(o);
693      }
694  
695      /**
696       * Removes all of the elements from this deque.
697 +     * The deque will be empty after this call returns.
698       */
699      public void clear() {
700          int h = head;
# Line 666 | Line 706 | public class ArrayDeque<E> extends Abstr
706              do {
707                  elements[i] = null;
708                  i = (i + 1) & mask;
709 <            } while(i != t);
709 >            } while (i != t);
710          }
711      }
712  
713      /**
714 <     * Returns an array containing all of the elements in this list
715 <     * in the correct order.
714 >     * Returns an array containing all of the elements in this deque
715 >     * in proper sequence (from first to last element).
716 >     *
717 >     * <p>The returned array will be "safe" in that no references to it are
718 >     * maintained by this deque.  (In other words, this method must allocate
719 >     * a new array).  The caller is thus free to modify the returned array.
720 >     *
721 >     * <p>This method acts as bridge between array-based and collection-based
722 >     * APIs.
723       *
724 <     * @return an array containing all of the elements in this list
678 <     *         in the correct order
724 >     * @return an array containing all of the elements in this deque
725       */
726      public Object[] toArray() {
727 <        return copyElements(new Object[size()]);
727 >        return copyElements(new Object[size()]);
728      }
729  
730      /**
731 <     * Returns an array containing all of the elements in this deque in the
732 <     * correct order; the runtime type of the returned array is that of the
733 <     * specified array.  If the deque fits in the specified array, it is
734 <     * returned therein.  Otherwise, a new array is allocated with the runtime
735 <     * type of the specified array and the size of this deque.
731 >     * Returns an array containing all of the elements in this deque in
732 >     * proper sequence (from first to last element); the runtime type of the
733 >     * returned array is that of the specified array.  If the deque fits in
734 >     * the specified array, it is returned therein.  Otherwise, a new array
735 >     * is allocated with the runtime type of the specified array and the
736 >     * size of this deque.
737       *
738 <     * <p>If the deque fits in the specified array with room to spare (i.e.,
739 <     * the array has more elements than the deque), the element in the array
740 <     * immediately following the end of the collection is set to <tt>null</tt>.
738 >     * <p>If this deque fits in the specified array with room to spare
739 >     * (i.e., the array has more elements than this deque), the element in
740 >     * the array immediately following the end of the deque is set to
741 >     * <tt>null</tt>.
742 >     *
743 >     * <p>Like the {@link #toArray()} method, this method acts as bridge between
744 >     * array-based and collection-based APIs.  Further, this method allows
745 >     * precise control over the runtime type of the output array, and may,
746 >     * under certain circumstances, be used to save allocation costs.
747 >     *
748 >     * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
749 >     * The following code can be used to dump the deque into a newly
750 >     * allocated array of <tt>String</tt>:
751 >     *
752 >     * <pre>
753 >     *     String[] y = x.toArray(new String[0]);</pre>
754 >     *
755 >     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
756 >     * <tt>toArray()</tt>.
757       *
758       * @param a the array into which the elements of the deque are to
759 <     *          be stored, if it is big enough; otherwise, a new array of the
760 <     *          same runtime type is allocated for this purpose
761 <     * @return an array containing the elements of the deque
762 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
763 <     *         of the runtime type of every element in this deque
759 >     *          be stored, if it is big enough; otherwise, a new array of the
760 >     *          same runtime type is allocated for this purpose
761 >     * @return an array containing all of the elements in this deque
762 >     * @throws ArrayStoreException if the runtime type of the specified array
763 >     *         is not a supertype of the runtime type of every element in
764 >     *         this deque
765 >     * @throws NullPointerException if the specified array is null
766       */
767      public <T> T[] toArray(T[] a) {
768          int size = size();
769          if (a.length < size)
770              a = (T[])java.lang.reflect.Array.newInstance(
771                      a.getClass().getComponentType(), size);
772 <        copyElements(a);
772 >        copyElements(a);
773          if (a.length > size)
774              a[size] = null;
775          return a;
# Line 718 | Line 783 | public class ArrayDeque<E> extends Abstr
783       * @return a copy of this deque
784       */
785      public ArrayDeque<E> clone() {
786 <        try {
786 >        try {
787              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
788 <            // 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);
788 >            result.elements = Arrays.copyOf(elements, elements.length);
789              return result;
790  
791 <        } catch (CloneNotSupportedException e) {
791 >        } catch (CloneNotSupportedException e) {
792              throw new AssertionError();
793          }
794      }
# Line 746 | Line 809 | public class ArrayDeque<E> extends Abstr
809          s.defaultWriteObject();
810  
811          // Write out size
812 <        int size = size();
750 <        s.writeInt(size);
812 >        s.writeInt(size());
813  
814          // Write out elements in order.
753        int i = head;
815          int mask = elements.length - 1;
816 <        for (int j = 0; j < size; j++) {
816 >        for (int i = head; i != tail; i = (i + 1) & mask)
817              s.writeObject(elements[i]);
757            i = (i + 1) & mask;
758        }
818      }
819  
820      /**
# Line 774 | Line 833 | public class ArrayDeque<E> extends Abstr
833          // Read in all elements in the proper order.
834          for (int i = 0; i < size; i++)
835              elements[i] = (E)s.readObject();
777
836      }
837   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines