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.30 by jsr166, Sun May 18 23:47:55 2008 UTC vs.
Revision 1.40 by jsr166, Sun Feb 26 22:43:03 2012 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 15 | Line 14 | import java.io.*;
14   * {@link Stack} when used as a stack, and faster than {@link LinkedList}
15   * when used as a queue.
16   *
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
21 < * iterator.remove()}, and the bulk operations, all of which run in linear
22 < * time.
17 > * <p>Most {@code ArrayDeque} operations run in amortized constant time.
18 > * Exceptions include
19 > * {@link #remove(Object) remove},
20 > * {@link #removeFirstOccurrence removeFirstOccurrence},
21 > * {@link #removeLastOccurrence removeLastOccurrence},
22 > * {@link #contains contains},
23 > * {@link #iterator iterator.remove()},
24 > * and the bulk operations, all of which run in linear time.
25   *
26 < * <p>The iterators returned by this class's <tt>iterator</tt> method are
27 < * <i>fail-fast</i>: If the deque is modified at any time after the iterator
28 < * is created, in any way except through the iterator's own <tt>remove</tt>
29 < * method, the iterator will generally throw a {@link
26 > * <p>The iterators returned by this class's {@link #iterator() iterator}
27 > * method are <em>fail-fast</em>: If the deque is modified at any time after
28 > * the iterator is created, in any way except through the iterator's own
29 > * {@code remove} method, the iterator will generally throw a {@link
30   * ConcurrentModificationException}.  Thus, in the face of concurrent
31   * modification, the iterator fails quickly and cleanly, rather than risking
32   * arbitrary, non-deterministic behavior at an undetermined time in the
# Line 34 | Line 35 | import java.io.*;
35   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
36   * as it is, generally speaking, impossible to make any hard guarantees in the
37   * presence of unsynchronized concurrent modification.  Fail-fast iterators
38 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
38 > * throw {@code ConcurrentModificationException} on a best-effort basis.
39   * Therefore, it would be wrong to write a program that depended on this
40   * exception for its correctness: <i>the fail-fast behavior of iterators
41   * should be used only to detect bugs.</i>
# Line 52 | Line 53 | import java.io.*;
53   * @param <E> the type of elements held in this collection
54   */
55   public class ArrayDeque<E> extends AbstractCollection<E>
56 <                           implements Deque<E>, Cloneable, Serializable
56 >                           implements Deque<E>, Cloneable, java.io.Serializable
57   {
58      /**
59       * The array in which the elements of the deque are stored.
# Line 64 | Line 65 | public class ArrayDeque<E> extends Abstr
65       * other.  We also guarantee that all array cells not holding
66       * deque elements are always null.
67       */
68 <    private transient E[] elements;
68 >    private transient Object[] elements;
69  
70      /**
71       * The index of the element at the head of the deque (which is the
# Line 88 | Line 89 | public class ArrayDeque<E> extends Abstr
89      // ******  Array allocation and resizing utilities ******
90  
91      /**
92 <     * Allocate empty array to hold the given number of elements.
92 >     * Allocates empty array to hold the given number of elements.
93       *
94       * @param numElements  the number of elements to hold
95       */
# Line 108 | Line 109 | public class ArrayDeque<E> extends Abstr
109              if (initialCapacity < 0)   // Too many elements, must back off
110                  initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
111          }
112 <        elements = (E[]) new Object[initialCapacity];
112 >        elements = new Object[initialCapacity];
113      }
114  
115      /**
116 <     * Double the capacity of this deque.  Call only when full, i.e.,
116 >     * Doubles the capacity of this deque.  Call only when full, i.e.,
117       * when head and tail have wrapped around to become equal.
118       */
119      private void doubleCapacity() {
# Line 126 | Line 127 | public class ArrayDeque<E> extends Abstr
127          Object[] a = new Object[newCapacity];
128          System.arraycopy(elements, p, a, 0, r);
129          System.arraycopy(elements, 0, a, r, p);
130 <        elements = (E[])a;
130 >        elements = a;
131          head = 0;
132          tail = n;
133      }
# Line 154 | Line 155 | public class ArrayDeque<E> extends Abstr
155       * sufficient to hold 16 elements.
156       */
157      public ArrayDeque() {
158 <        elements = (E[]) new Object[16];
158 >        elements = new Object[16];
159      }
160  
161      /**
# Line 220 | Line 221 | public class ArrayDeque<E> extends Abstr
221       * Inserts the specified element at the front of this deque.
222       *
223       * @param e the element to add
224 <     * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
224 >     * @return {@code true} (as specified by {@link Deque#offerFirst})
225       * @throws NullPointerException if the specified element is null
226       */
227      public boolean offerFirst(E e) {
# Line 232 | Line 233 | public class ArrayDeque<E> extends Abstr
233       * Inserts the specified element at the end of this deque.
234       *
235       * @param e the element to add
236 <     * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
236 >     * @return {@code true} (as specified by {@link Deque#offerLast})
237       * @throws NullPointerException if the specified element is null
238       */
239      public boolean offerLast(E e) {
# Line 262 | Line 263 | public class ArrayDeque<E> extends Abstr
263  
264      public E pollFirst() {
265          int h = head;
266 <        E result = elements[h]; // Element is null if deque empty
266 >        @SuppressWarnings("unchecked")
267 >        E result = (E) elements[h];
268 >        // Element is null if deque empty
269          if (result == null)
270              return null;
271          elements[h] = null;     // Must null out slot
# Line 272 | Line 275 | public class ArrayDeque<E> extends Abstr
275  
276      public E pollLast() {
277          int t = (tail - 1) & (elements.length - 1);
278 <        E result = elements[t];
278 >        @SuppressWarnings("unchecked")
279 >        E result = (E) elements[t];
280          if (result == null)
281              return null;
282          elements[t] = null;
# Line 284 | Line 288 | public class ArrayDeque<E> extends Abstr
288       * @throws NoSuchElementException {@inheritDoc}
289       */
290      public E getFirst() {
291 <        E x = elements[head];
292 <        if (x == null)
291 >        @SuppressWarnings("unchecked")
292 >        E result = (E) elements[head];
293 >        if (result == null)
294              throw new NoSuchElementException();
295 <        return x;
295 >        return result;
296      }
297  
298      /**
299       * @throws NoSuchElementException {@inheritDoc}
300       */
301      public E getLast() {
302 <        E x = elements[(tail - 1) & (elements.length - 1)];
303 <        if (x == null)
302 >        @SuppressWarnings("unchecked")
303 >        E result = (E) elements[(tail - 1) & (elements.length - 1)];
304 >        if (result == null)
305              throw new NoSuchElementException();
306 <        return x;
306 >        return result;
307      }
308  
309 +    @SuppressWarnings("unchecked")
310      public E peekFirst() {
311 <        return elements[head]; // elements[head] is null if deque empty
311 >        // elements[head] is null if deque empty
312 >        return (E) elements[head];
313      }
314  
315 +    @SuppressWarnings("unchecked")
316      public E peekLast() {
317 <        return elements[(tail - 1) & (elements.length - 1)];
317 >        return (E) elements[(tail - 1) & (elements.length - 1)];
318      }
319  
320      /**
321       * Removes the first occurrence of the specified element in this
322       * deque (when traversing the deque from head to tail).
323       * If the deque does not contain the element, it is unchanged.
324 <     * More formally, removes the first element <tt>e</tt> such that
325 <     * <tt>o.equals(e)</tt> (if such an element exists).
326 <     * Returns <tt>true</tt> if this deque contained the specified element
324 >     * More formally, removes the first element {@code e} such that
325 >     * {@code o.equals(e)} (if such an element exists).
326 >     * Returns {@code true} if this deque contained the specified element
327       * (or equivalently, if this deque changed as a result of the call).
328       *
329       * @param o element to be removed from this deque, if present
330 <     * @return <tt>true</tt> if the deque contained the specified element
330 >     * @return {@code true} if the deque contained the specified element
331       */
332      public boolean removeFirstOccurrence(Object o) {
333          if (o == null)
334              return false;
335          int mask = elements.length - 1;
336          int i = head;
337 <        E x;
337 >        Object x;
338          while ( (x = elements[i]) != null) {
339              if (o.equals(x)) {
340                  delete(i);
# Line 340 | Line 349 | public class ArrayDeque<E> extends Abstr
349       * Removes the last occurrence of the specified element in this
350       * deque (when traversing the deque from head to tail).
351       * If the deque does not contain the element, it is unchanged.
352 <     * More formally, removes the last element <tt>e</tt> such that
353 <     * <tt>o.equals(e)</tt> (if such an element exists).
354 <     * Returns <tt>true</tt> if this deque contained the specified element
352 >     * More formally, removes the last element {@code e} such that
353 >     * {@code o.equals(e)} (if such an element exists).
354 >     * Returns {@code true} if this deque contained the specified element
355       * (or equivalently, if this deque changed as a result of the call).
356       *
357       * @param o element to be removed from this deque, if present
358 <     * @return <tt>true</tt> if the deque contained the specified element
358 >     * @return {@code true} if the deque contained the specified element
359       */
360      public boolean removeLastOccurrence(Object o) {
361          if (o == null)
362              return false;
363          int mask = elements.length - 1;
364          int i = (tail - 1) & mask;
365 <        E x;
365 >        Object x;
366          while ( (x = elements[i]) != null) {
367              if (o.equals(x)) {
368                  delete(i);
# Line 372 | Line 381 | public class ArrayDeque<E> extends Abstr
381       * <p>This method is equivalent to {@link #addLast}.
382       *
383       * @param e the element to add
384 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
384 >     * @return {@code true} (as specified by {@link Collection#add})
385       * @throws NullPointerException if the specified element is null
386       */
387      public boolean add(E e) {
# Line 386 | Line 395 | public class ArrayDeque<E> extends Abstr
395       * <p>This method is equivalent to {@link #offerLast}.
396       *
397       * @param e the element to add
398 <     * @return <tt>true</tt> (as specified by {@link Queue#offer})
398 >     * @return {@code true} (as specified by {@link Queue#offer})
399       * @throws NullPointerException if the specified element is null
400       */
401      public boolean offer(E e) {
# Line 411 | Line 420 | public class ArrayDeque<E> extends Abstr
420      /**
421       * Retrieves and removes the head of the queue represented by this deque
422       * (in other words, the first element of this deque), or returns
423 <     * <tt>null</tt> if this deque is empty.
423 >     * {@code null} if this deque is empty.
424       *
425       * <p>This method is equivalent to {@link #pollFirst}.
426       *
427       * @return the head of the queue represented by this deque, or
428 <     *         <tt>null</tt> if this deque is empty
428 >     *         {@code null} if this deque is empty
429       */
430      public E poll() {
431          return pollFirst();
# Line 438 | Line 447 | public class ArrayDeque<E> extends Abstr
447  
448      /**
449       * Retrieves, but does not remove, the head of the queue represented by
450 <     * this deque, or returns <tt>null</tt> if this deque is empty.
450 >     * this deque, or returns {@code null} if this deque is empty.
451       *
452       * <p>This method is equivalent to {@link #peekFirst}.
453       *
454       * @return the head of the queue represented by this deque, or
455 <     *         <tt>null</tt> if this deque is empty
455 >     *         {@code null} if this deque is empty
456       */
457      public E peek() {
458          return peekFirst();
# Line 498 | Line 507 | public class ArrayDeque<E> extends Abstr
507       */
508      private boolean delete(int i) {
509          checkInvariants();
510 <        final E[] elements = this.elements;
510 >        final Object[] elements = this.elements;
511          final int mask = elements.length - 1;
512          final int h = head;
513          final int t = tail;
# Line 547 | Line 556 | public class ArrayDeque<E> extends Abstr
556      }
557  
558      /**
559 <     * Returns <tt>true</tt> if this deque contains no elements.
559 >     * Returns {@code true} if this deque contains no elements.
560       *
561 <     * @return <tt>true</tt> if this deque contains no elements
561 >     * @return {@code true} if this deque contains no elements
562       */
563      public boolean isEmpty() {
564          return head == tail;
# Line 596 | Line 605 | public class ArrayDeque<E> extends Abstr
605          public E next() {
606              if (cursor == fence)
607                  throw new NoSuchElementException();
608 <            E result = elements[cursor];
608 >            @SuppressWarnings("unchecked")
609 >            E result = (E) elements[cursor];
610              // This check doesn't catch all possible comodifications,
611              // but does catch the ones that corrupt traversal
612              if (tail != fence || result == null)
# Line 635 | Line 645 | public class ArrayDeque<E> extends Abstr
645              if (cursor == fence)
646                  throw new NoSuchElementException();
647              cursor = (cursor - 1) & (elements.length - 1);
648 <            E result = elements[cursor];
648 >            @SuppressWarnings("unchecked")
649 >            E result = (E) elements[cursor];
650              if (head != fence || result == null)
651                  throw new ConcurrentModificationException();
652              lastRet = cursor;
# Line 654 | Line 665 | public class ArrayDeque<E> extends Abstr
665      }
666  
667      /**
668 <     * Returns <tt>true</tt> if this deque contains the specified element.
669 <     * More formally, returns <tt>true</tt> if and only if this deque contains
670 <     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
668 >     * Returns {@code true} if this deque contains the specified element.
669 >     * More formally, returns {@code true} if and only if this deque contains
670 >     * at least one element {@code e} such that {@code o.equals(e)}.
671       *
672       * @param o object to be checked for containment in this deque
673 <     * @return <tt>true</tt> if this deque contains the specified element
673 >     * @return {@code true} if this deque contains the specified element
674       */
675      public boolean contains(Object o) {
676          if (o == null)
677              return false;
678          int mask = elements.length - 1;
679          int i = head;
680 <        E x;
680 >        Object x;
681          while ( (x = elements[i]) != null) {
682              if (o.equals(x))
683                  return true;
# Line 678 | Line 689 | public class ArrayDeque<E> extends Abstr
689      /**
690       * Removes a single instance of the specified element from this deque.
691       * If the deque does not contain the element, it is unchanged.
692 <     * More formally, removes the first element <tt>e</tt> such that
693 <     * <tt>o.equals(e)</tt> (if such an element exists).
694 <     * Returns <tt>true</tt> if this deque contained the specified element
692 >     * More formally, removes the first element {@code e} such that
693 >     * {@code o.equals(e)} (if such an element exists).
694 >     * Returns {@code true} if this deque contained the specified element
695       * (or equivalently, if this deque changed as a result of the call).
696       *
697       * <p>This method is equivalent to {@link #removeFirstOccurrence}.
698       *
699       * @param o element to be removed from this deque, if present
700 <     * @return <tt>true</tt> if this deque contained the specified element
700 >     * @return {@code true} if this deque contained the specified element
701       */
702      public boolean remove(Object o) {
703          return removeFirstOccurrence(o);
# Line 738 | Line 749 | public class ArrayDeque<E> extends Abstr
749       * <p>If this deque fits in the specified array with room to spare
750       * (i.e., the array has more elements than this deque), the element in
751       * the array immediately following the end of the deque is set to
752 <     * <tt>null</tt>.
752 >     * {@code null}.
753       *
754       * <p>Like the {@link #toArray()} method, this method acts as bridge between
755       * array-based and collection-based APIs.  Further, this method allows
756       * precise control over the runtime type of the output array, and may,
757       * under certain circumstances, be used to save allocation costs.
758       *
759 <     * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
759 >     * <p>Suppose {@code x} is a deque known to contain only strings.
760       * The following code can be used to dump the deque into a newly
761 <     * allocated array of <tt>String</tt>:
761 >     * allocated array of {@code String}:
762       *
763 <     * <pre>
753 <     *     String[] y = x.toArray(new String[0]);</pre>
763 >     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
764       *
765 <     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
766 <     * <tt>toArray()</tt>.
765 >     * Note that {@code toArray(new Object[0])} is identical in function to
766 >     * {@code toArray()}.
767       *
768       * @param a the array into which the elements of the deque are to
769       *          be stored, if it is big enough; otherwise, a new array of the
# Line 764 | Line 774 | public class ArrayDeque<E> extends Abstr
774       *         this deque
775       * @throws NullPointerException if the specified array is null
776       */
777 +    @SuppressWarnings("unchecked")
778      public <T> T[] toArray(T[] a) {
779          int size = size();
780          if (a.length < size)
# Line 784 | Line 795 | public class ArrayDeque<E> extends Abstr
795       */
796      public ArrayDeque<E> clone() {
797          try {
798 +            @SuppressWarnings("unchecked")
799              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
800              result.elements = Arrays.copyOf(elements, elements.length);
801              return result;
790
802          } catch (CloneNotSupportedException e) {
803              throw new AssertionError();
804          }
805      }
806  
796    /**
797     * Appease the serialization gods.
798     */
807      private static final long serialVersionUID = 2340985798034038923L;
808  
809      /**
810 <     * Serialize this deque.
810 >     * Saves this deque to a stream (that is, serializes it).
811       *
812 <     * @serialData The current size (<tt>int</tt>) of the deque,
812 >     * @serialData The current size ({@code int}) of the deque,
813       * followed by all of its elements (each an object reference) in
814       * first-to-last order.
815       */
816 <    private void writeObject(ObjectOutputStream s) throws IOException {
816 >    private void writeObject(java.io.ObjectOutputStream s)
817 >            throws java.io.IOException {
818          s.defaultWriteObject();
819  
820          // Write out size
# Line 818 | Line 827 | public class ArrayDeque<E> extends Abstr
827      }
828  
829      /**
830 <     * Deserialize this deque.
830 >     * Reconstitutes this deque from a stream (that is, deserializes it).
831       */
832 <    private void readObject(ObjectInputStream s)
833 <            throws IOException, ClassNotFoundException {
832 >    private void readObject(java.io.ObjectInputStream s)
833 >            throws java.io.IOException, ClassNotFoundException {
834          s.defaultReadObject();
835  
836          // Read in size and allocate array
# Line 832 | Line 841 | public class ArrayDeque<E> extends Abstr
841  
842          // Read in all elements in the proper order.
843          for (int i = 0; i < size; i++)
844 <            elements[i] = (E)s.readObject();
844 >            elements[i] = s.readObject();
845      }
846   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines