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.9 by jsr166, Mon May 16 06:16:12 2005 UTC vs.
Revision 1.30 by jsr166, Sun May 18 23:47:55 2008 UTC

# Line 44 | Line 44 | import java.io.*;
44   * Iterator} interfaces.
45   *
46   * <p>This class is a member of the
47 < * <a href="{@docRoot}/../guide/collections/index.html">
47 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
48   * Java Collections Framework</a>.
49   *
50   * @author  Josh Bloch and Doug Lea
# Line 202 | Line 202 | public class ArrayDeque<E> extends Abstr
202  
203      /**
204       * Inserts the specified element at the end of this deque.
205 <     * This method is equivalent to {@link #add} and {@link #push}.
205 >     *
206 >     * <p>This method is equivalent to {@link #add}.
207       *
208       * @param e the element to add
209       * @throws NullPointerException if the specified element is null
# Line 219 | Line 220 | public class ArrayDeque<E> extends Abstr
220       * Inserts the specified element at the front of this deque.
221       *
222       * @param e the element to add
223 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerFirst})
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) {
# Line 231 | Line 232 | public class ArrayDeque<E> extends Abstr
232       * Inserts the specified element at the end of this deque.
233       *
234       * @param e the element to add
235 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerLast})
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) {
# Line 313 | Line 314 | public class ArrayDeque<E> extends Abstr
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 true if this deque contained the specified element (or
318 <     * equivalently, if this deque changed as a result of the call).
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 o element to be removed from this deque, if present
321       * @return <tt>true</tt> if the deque contained the specified element
# Line 341 | Line 342 | public class ArrayDeque<E> extends Abstr
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 true if this deque contained the specified element (or
346 <     * equivalently, if this deque changed as a result of the call).
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 o element to be removed from this deque, if present
349       * @return <tt>true</tt> if the deque contained the specified element
# Line 371 | Line 372 | public class ArrayDeque<E> extends Abstr
372       * <p>This method is equivalent to {@link #addLast}.
373       *
374       * @param e the element to add
375 <     * @return <tt>true</tt> (as per the spec for {@link Collection#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) {
# Line 385 | Line 386 | public class ArrayDeque<E> extends Abstr
386       * <p>This method is equivalent to {@link #offerLast}.
387       *
388       * @param e the element to add
389 <     * @return <tt>true</tt> (as per the spec for {@link Queue#offer})
389 >     * @return <tt>true</tt> (as specified by {@link Queue#offer})
390       * @throws NullPointerException if the specified element is null
391       */
392      public boolean offer(E e) {
# Line 394 | Line 395 | public class ArrayDeque<E> extends Abstr
395  
396      /**
397       * Retrieves and removes the head of the queue represented by this deque.
398 <     * This method differs from {@link #poll} only 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}.
# Line 422 | Line 424 | public class ArrayDeque<E> extends Abstr
424  
425      /**
426       * Retrieves, but does not remove, the head of the queue represented by
427 <     * this deque.  This method differs from {@link #peek} only in that it
428 <     * throws an exception if this deque is empty.
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}.
431       *
# Line 476 | Line 478 | public class ArrayDeque<E> extends Abstr
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       * Removes the element at the specified position in the elements array,
491       * adjusting head and tail as necessary.  This can result in motion of
# Line 487 | Line 497 | public class ArrayDeque<E> extends Abstr
497       * @return true if elements moved backwards
498       */
499      private boolean delete(int i) {
500 <        int mask = elements.length - 1;
501 <
502 <        // Invariant: head <= i < tail mod circularity
503 <        if (((i - head) & mask) >= ((tail - head) & mask))
504 <            throw new ConcurrentModificationException();
505 <
506 <        // Case 1: Deque doesn't wrap
507 <        // Case 2: Deque does wrap and removed element is in the head portion
508 <        if (i >= head) {
509 <            System.arraycopy(elements, head, elements, head + 1, i - head);
510 <            elements[head] = null;
511 <            head = (head + 1) & mask;
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          }
504
505        // Case 3: Deque wraps and removed element is in the tail portion
506        tail--;
507        System.arraycopy(elements, i + 1, elements, i, tail - i);
508        elements[tail] = null;
509        return true;
536      }
537  
538      // *** Collection Methods ***
# Line 535 | Line 561 | public class ArrayDeque<E> extends Abstr
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
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 564 | Line 594 | public class ArrayDeque<E> extends Abstr
594          }
595  
596          public E next() {
567            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 579 | 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;
585            fence = tail;
653          }
654      }
655  
# Line 613 | Line 680 | public class ArrayDeque<E> extends Abstr
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 true if this deque contained the specified element (or
684 <     * equivalently, if this deque changed as a result of the call).
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       *
# Line 645 | Line 712 | public class ArrayDeque<E> extends Abstr
712  
713      /**
714       * Returns an array containing all of the elements in this deque
715 <     * in the correct order.
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 deque
651     *         in the correct order
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 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>If the deque fits in the specified array with room to spare (i.e.,
749 <     * the array has more elements than the deque), the element in the array
750 <     * immediately following the end of the collection is set to <tt>null</tt>.
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
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 693 | Line 785 | public class ArrayDeque<E> extends Abstr
785      public ArrayDeque<E> clone() {
786          try {
787              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
788 <            // These two lines are currently faster than cloning the array:
697 <            result.elements = (E[]) new Object[elements.length];
698 <            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) {
# Line 719 | Line 809 | public class ArrayDeque<E> extends Abstr
809          s.defaultWriteObject();
810  
811          // Write out size
812 <        int size = size();
723 <        s.writeInt(size);
812 >        s.writeInt(size());
813  
814          // Write out elements in order.
726        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]);
730            i = (i + 1) & mask;
731        }
818      }
819  
820      /**
# Line 747 | 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();
750
836      }
837   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines