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.50 by jsr166, Wed Feb 20 12:32:01 2013 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 > import java.io.Serializable;
8 > import java.util.function.Consumer;
9 > import java.util.stream.Stream;
10 > import java.util.stream.Streams;
11  
12   /**
13   * Resizable-array implementation of the {@link Deque} interface.  Array
# Line 15 | Line 18 | import java.io.*;
18   * {@link Stack} when used as a stack, and faster than {@link LinkedList}
19   * when used as a queue.
20   *
21 < * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
21 > * <p>Most {@code ArrayDeque} operations run in amortized constant time.
22   * Exceptions include {@link #remove(Object) remove}, {@link
23   * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
24 < * removeLastOccurrence}, {@link #contains contains }, {@link #iterator
24 > * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
25   * iterator.remove()}, and the bulk operations, all of which run in linear
26   * time.
27   *
28 < * <p>The iterators returned by this class's <tt>iterator</tt> method are
28 > * <p>The iterators returned by this class's {@code iterator} method are
29   * <i>fail-fast</i>: If the deque is modified at any time after the iterator
30 < * is created, in any way except through the iterator's own remove method, the
31 < * iterator will generally throw a {@link ConcurrentModificationException}.
32 < * Thus, in the face of concurrent modification, the iterator fails quickly
33 < * and cleanly, rather than risking arbitrary, non-deterministic behavior at
34 < * an undetermined time in the future.
30 > * is created, in any way except through the iterator's own {@code remove}
31 > * method, the iterator will generally throw a {@link
32 > * ConcurrentModificationException}.  Thus, in the face of concurrent
33 > * modification, the iterator fails quickly and cleanly, rather than risking
34 > * arbitrary, non-deterministic behavior at an undetermined time in the
35 > * future.
36   *
37   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
38   * as it is, generally speaking, impossible to make any hard guarantees in the
39   * presence of unsynchronized concurrent modification.  Fail-fast iterators
40 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
40 > * throw {@code ConcurrentModificationException} on a best-effort basis.
41   * Therefore, it would be wrong to write a program that depended on this
42   * exception for its correctness: <i>the fail-fast behavior of iterators
43   * should be used only to detect bugs.</i>
44   *
45   * <p>This class and its iterator implement all of the
46 < * optional methods of the {@link Collection} and {@link
47 < * Iterator} interfaces.  This class is a member of the <a
48 < * href="{@docRoot}/../guide/collections/index.html"> Java Collections
49 < * Framework</a>.
46 > * <em>optional</em> methods of the {@link Collection} and {@link
47 > * Iterator} interfaces.
48 > *
49 > * <p>This class is a member of the
50 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
51 > * Java Collections Framework</a>.
52   *
53   * @author  Josh Bloch and Doug Lea
54   * @since   1.6
# Line 61 | Line 67 | public class ArrayDeque<E> extends Abstr
67       * other.  We also guarantee that all array cells not holding
68       * deque elements are always null.
69       */
70 <    private transient E[] elements;
70 >    transient Object[] elements; // non-private to simplify nested class access
71  
72      /**
73       * The index of the element at the head of the deque (which is the
74       * element that would be removed by remove() or pop()); or an
75       * arbitrary number equal to tail if the deque is empty.
76       */
77 <    private transient int head;
77 >    transient int head;
78  
79      /**
80       * The index at which the next element would be added to the tail
81       * of the deque (via addLast(E), add(E), or push(E)).
82       */
83 <    private transient int tail;
83 >    transient int tail;
84  
85      /**
86       * The minimum capacity that we'll use for a newly created deque.
# Line 85 | Line 91 | public class ArrayDeque<E> extends Abstr
91      // ******  Array allocation and resizing utilities ******
92  
93      /**
94 <     * Allocate empty array to hold the given number of elements.
94 >     * Allocates empty array to hold the given number of elements.
95       *
96 <     * @param numElements  the number of elements to hold.
96 >     * @param numElements  the number of elements to hold
97       */
98 <    private void allocateElements(int numElements) {  
98 >    private void allocateElements(int numElements) {
99          int initialCapacity = MIN_INITIAL_CAPACITY;
100          // Find the best power of two to hold elements.
101          // Tests "<=" because arrays aren't kept full.
# Line 105 | Line 111 | public class ArrayDeque<E> extends Abstr
111              if (initialCapacity < 0)   // Too many elements, must back off
112                  initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
113          }
114 <        elements = (E[]) new Object[initialCapacity];
114 >        elements = new Object[initialCapacity];
115      }
116  
117      /**
118 <     * Double the capacity of this deque.  Call only when full, i.e.,
118 >     * Doubles the capacity of this deque.  Call only when full, i.e.,
119       * when head and tail have wrapped around to become equal.
120       */
121      private void doubleCapacity() {
122 <        assert head == tail;
122 >        assert head == tail;
123          int p = head;
124          int n = elements.length;
125          int r = n - p; // number of elements to the right of p
# Line 123 | Line 129 | public class ArrayDeque<E> extends Abstr
129          Object[] a = new Object[newCapacity];
130          System.arraycopy(elements, p, a, 0, r);
131          System.arraycopy(elements, 0, a, r, p);
132 <        elements = (E[])a;
132 >        elements = a;
133          head = 0;
134          tail = n;
135      }
136  
137      /**
132     * Copy the elements from our element array into the specified array,
133     * in order (from first to last element in the deque).  It is assumed
134     * that the array is large enough to hold all elements in the deque.
135     *
136     * @return its argument
137     */
138    private <T> T[] copyElements(T[] a) {
139        if (head < tail) {
140            System.arraycopy(elements, head, a, 0, size());
141        } else if (head > tail) {
142            int headPortionLen = elements.length - head;
143            System.arraycopy(elements, head, a, 0, headPortionLen);
144            System.arraycopy(elements, 0, a, headPortionLen, tail);
145        }
146        return a;
147    }
148
149    /**
138       * Constructs an empty array deque with an initial capacity
139       * sufficient to hold 16 elements.
140       */
141      public ArrayDeque() {
142 <        elements = (E[]) new Object[16];
142 >        elements = new Object[16];
143      }
144  
145      /**
# Line 184 | Line 172 | public class ArrayDeque<E> extends Abstr
172      // terms of these.
173  
174      /**
175 <     * Inserts the specified element to the front this deque.
175 >     * Inserts the specified element at the front of this deque.
176       *
177 <     * @param e the element to insert
178 <     * @throws NullPointerException if <tt>e</tt> is null
177 >     * @param e the element to add
178 >     * @throws NullPointerException if the specified element is null
179       */
180      public void addFirst(E e) {
181          if (e == null)
182              throw new NullPointerException();
183          elements[head = (head - 1) & (elements.length - 1)] = e;
184 <        if (head == tail)
184 >        if (head == tail)
185              doubleCapacity();
186      }
187  
188      /**
189 <     * Inserts the specified element to the end this deque.
202 <     * This method is equivalent to {@link Collection#add} and
203 <     * {@link #push}.
189 >     * Inserts the specified element at the end of this deque.
190       *
191 <     * @param e the element to insert
192 <     * @throws NullPointerException if <tt>e</tt> is null
191 >     * <p>This method is equivalent to {@link #add}.
192 >     *
193 >     * @param e the element to add
194 >     * @throws NullPointerException if the specified element is null
195       */
196      public void addLast(E e) {
197          if (e == null)
# Line 214 | Line 202 | public class ArrayDeque<E> extends Abstr
202      }
203  
204      /**
205 <     * 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.
205 >     * Inserts the specified element at the front of this deque.
206       *
207 <     * @param e the element to insert
208 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerFirst})
209 <     * @throws NullPointerException if <tt>e</tt> is null
207 >     * @param e the element to add
208 >     * @return {@code true} (as specified by {@link Deque#offerFirst})
209 >     * @throws NullPointerException if the specified element is null
210       */
211      public boolean offerFirst(E e) {
212          addFirst(e);
# Line 260 | Line 214 | public class ArrayDeque<E> extends Abstr
214      }
215  
216      /**
217 <     * Inserts the specified element to the end this deque.
217 >     * Inserts the specified element at the end of this deque.
218       *
219 <     * @param e the element to insert
220 <     * @return <tt>true</tt> (as per the spec for {@link Deque#offerLast})
221 <     * @throws NullPointerException if <tt>e</tt> is null
219 >     * @param e the element to add
220 >     * @return {@code true} (as specified by {@link Deque#offerLast})
221 >     * @throws NullPointerException if the specified element is null
222       */
223      public boolean offerLast(E e) {
224          addLast(e);
# Line 272 | Line 226 | public class ArrayDeque<E> extends Abstr
226      }
227  
228      /**
229 <     * 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
229 >     * @throws NoSuchElementException {@inheritDoc}
230       */
231      public E removeFirst() {
232          E x = pollFirst();
# Line 287 | Line 236 | public class ArrayDeque<E> extends Abstr
236      }
237  
238      /**
239 <     * 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
239 >     * @throws NoSuchElementException {@inheritDoc}
240       */
241      public E removeLast() {
242          E x = pollLast();
# Line 301 | Line 245 | public class ArrayDeque<E> extends Abstr
245          return x;
246      }
247  
248 <    /**
249 <     * Retrieves, but does not remove, the first element of this deque,
250 <     * returning <tt>null</tt> if this deque is empty.
251 <     *
252 <     * @return the first element of this deque, or <tt>null</tt> if
253 <     *     this deque is empty
254 <     */
255 <    public E peekFirst() {
256 <        return elements[head]; // elements[head] is null if deque empty
248 >    public E pollFirst() {
249 >        int h = head;
250 >        @SuppressWarnings("unchecked")
251 >        E result = (E) elements[h];
252 >        // Element is null if deque empty
253 >        if (result == null)
254 >            return null;
255 >        elements[h] = null;     // Must null out slot
256 >        head = (h + 1) & (elements.length - 1);
257 >        return result;
258      }
259  
260 <    /**
261 <     * Retrieves, but does not remove, the last element of this deque,
262 <     * returning <tt>null</tt> if this deque is empty.
263 <     *
264 <     * @return the last element of this deque, or <tt>null</tt> if this deque
265 <     *     is empty
266 <     */
267 <    public E peekLast() {
268 <        return elements[(tail - 1) & (elements.length - 1)];
260 >    public E pollLast() {
261 >        int t = (tail - 1) & (elements.length - 1);
262 >        @SuppressWarnings("unchecked")
263 >        E result = (E) elements[t];
264 >        if (result == null)
265 >            return null;
266 >        elements[t] = null;
267 >        tail = t;
268 >        return result;
269      }
270  
271      /**
272 <     * 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
272 >     * @throws NoSuchElementException {@inheritDoc}
273       */
274      public E getFirst() {
275 <        E x = elements[head];
276 <        if (x == null)
275 >        @SuppressWarnings("unchecked")
276 >        E result = (E) elements[head];
277 >        if (result == null)
278              throw new NoSuchElementException();
279 <        return x;
279 >        return result;
280      }
281  
282      /**
283 <     * 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
283 >     * @throws NoSuchElementException {@inheritDoc}
284       */
285      public E getLast() {
286 <        E x = elements[(tail - 1) & (elements.length - 1)];
287 <        if (x == null)
286 >        @SuppressWarnings("unchecked")
287 >        E result = (E) elements[(tail - 1) & (elements.length - 1)];
288 >        if (result == null)
289              throw new NoSuchElementException();
290 <        return x;
290 >        return result;
291 >    }
292 >
293 >    @SuppressWarnings("unchecked")
294 >    public E peekFirst() {
295 >        // elements[head] is null if deque empty
296 >        return (E) elements[head];
297 >    }
298 >
299 >    @SuppressWarnings("unchecked")
300 >    public E peekLast() {
301 >        return (E) elements[(tail - 1) & (elements.length - 1)];
302      }
303  
304      /**
305       * Removes the first occurrence of the specified element in this
306 <     * deque (when traversing the deque from head to tail).  If the deque
307 <     * does not contain the element, it is unchanged.
306 >     * deque (when traversing the deque from head to tail).
307 >     * If the deque does not contain the element, it is unchanged.
308 >     * More formally, removes the first element {@code e} such that
309 >     * {@code o.equals(e)} (if such an element exists).
310 >     * Returns {@code true} if this deque contained the specified element
311 >     * (or equivalently, if this deque changed as a result of the call).
312       *
313 <     * @param e element to be removed from this deque, if present
314 <     * @return <tt>true</tt> if the deque contained the specified element
313 >     * @param o element to be removed from this deque, if present
314 >     * @return {@code true} if the deque contained the specified element
315       */
316 <    public boolean removeFirstOccurrence(Object e) {
317 <        if (e == null)
316 >    public boolean removeFirstOccurrence(Object o) {
317 >        if (o == null)
318              return false;
319          int mask = elements.length - 1;
320          int i = head;
321 <        E x;
321 >        Object x;
322          while ( (x = elements[i]) != null) {
323 <            if (e.equals(x)) {
323 >            if (o.equals(x)) {
324                  delete(i);
325                  return true;
326              }
# Line 379 | Line 331 | public class ArrayDeque<E> extends Abstr
331  
332      /**
333       * Removes the last occurrence of the specified element in this
334 <     * deque (when traversing the deque from head to tail).  If the deque
335 <     * does not contain the element, it is unchanged.
334 >     * deque (when traversing the deque from head to tail).
335 >     * If the deque does not contain the element, it is unchanged.
336 >     * More formally, removes the last element {@code e} such that
337 >     * {@code o.equals(e)} (if such an element exists).
338 >     * Returns {@code true} if this deque contained the specified element
339 >     * (or equivalently, if this deque changed as a result of the call).
340       *
341 <     * @param e element to be removed from this deque, if present
342 <     * @return <tt>true</tt> if the deque contained the specified element
341 >     * @param o element to be removed from this deque, if present
342 >     * @return {@code true} if the deque contained the specified element
343       */
344 <    public boolean removeLastOccurrence(Object e) {
345 <        if (e == null)
344 >    public boolean removeLastOccurrence(Object o) {
345 >        if (o == null)
346              return false;
347          int mask = elements.length - 1;
348          int i = (tail - 1) & mask;
349 <        E x;
349 >        Object x;
350          while ( (x = elements[i]) != null) {
351 <            if (e.equals(x)) {
351 >            if (o.equals(x)) {
352                  delete(i);
353                  return true;
354              }
# Line 404 | Line 360 | public class ArrayDeque<E> extends Abstr
360      // *** Queue methods ***
361  
362      /**
363 <     * 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.
363 >     * Inserts the specified element at the end of this deque.
364       *
365       * <p>This method is equivalent to {@link #addLast}.
366       *
367 <     * @param e the element to insert
368 <     * @return <tt>true</tt> (as per the spec for {@link Collection#add})
369 <     * @throws NullPointerException if <tt>e</tt> is null
367 >     * @param e the element to add
368 >     * @return {@code true} (as specified by {@link Collection#add})
369 >     * @throws NullPointerException if the specified element is null
370       */
371      public boolean add(E e) {
372          addLast(e);
# Line 431 | Line 374 | public class ArrayDeque<E> extends Abstr
374      }
375  
376      /**
377 <     * 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.
377 >     * Inserts the specified element at the end of this deque.
378       *
379 <     * <p>This method is equivalent to {@link #pollFirst}.
379 >     * <p>This method is equivalent to {@link #offerLast}.
380       *
381 <     * @return the first element of this deque, or <tt>null</tt> if
382 <     *     this deque is empty
381 >     * @param e the element to add
382 >     * @return {@code true} (as specified by {@link Queue#offer})
383 >     * @throws NullPointerException if the specified element is null
384       */
385 <    public E poll() {
386 <        return pollFirst();
385 >    public boolean offer(E e) {
386 >        return offerLast(e);
387      }
388  
389      /**
390       * Retrieves and removes the head of the queue represented by this deque.
391 <     * This method differs from the <tt>poll</tt> method in that it throws an
391 >     *
392 >     * This method differs from {@link #poll poll} only in that it throws an
393       * exception if this deque is empty.
394       *
395       * <p>This method is equivalent to {@link #removeFirst}.
396       *
397       * @return the head of the queue represented by this deque
398 <     * @throws NoSuchElementException if this deque is empty
398 >     * @throws NoSuchElementException {@inheritDoc}
399       */
400      public E remove() {
401          return removeFirst();
402      }
403  
404      /**
405 <     * Retrieves, but does not remove, the head of the queue represented by
406 <     * this deque, returning <tt>null</tt> if this deque is empty.
405 >     * Retrieves and removes the head of the queue represented by this deque
406 >     * (in other words, the first element of this deque), or returns
407 >     * {@code null} if this deque is empty.
408       *
409 <     * <p>This method is equivalent to {@link #peekFirst}
409 >     * <p>This method is equivalent to {@link #pollFirst}.
410       *
411       * @return the head of the queue represented by this deque, or
412 <     *     <tt>null</tt> if this deque is empty
412 >     *         {@code null} if this deque is empty
413       */
414 <    public E peek() {
415 <        return peekFirst();
414 >    public E poll() {
415 >        return pollFirst();
416      }
417  
418      /**
419       * Retrieves, but does not remove, the head of the queue represented by
420 <     * this deque.  This method differs from the <tt>peek</tt> method only in
420 >     * this deque.  This method differs from {@link #peek peek} only in
421       * that it throws an exception if this deque is empty.
422       *
423 <     * <p>This method is equivalent to {@link #getFirst}
423 >     * <p>This method is equivalent to {@link #getFirst}.
424       *
425       * @return the head of the queue represented by this deque
426 <     * @throws NoSuchElementException if this deque is empty
426 >     * @throws NoSuchElementException {@inheritDoc}
427       */
428      public E element() {
429          return getFirst();
430      }
431  
432 +    /**
433 +     * Retrieves, but does not remove, the head of the queue represented by
434 +     * this deque, or returns {@code null} if this deque is empty.
435 +     *
436 +     * <p>This method is equivalent to {@link #peekFirst}.
437 +     *
438 +     * @return the head of the queue represented by this deque, or
439 +     *         {@code null} if this deque is empty
440 +     */
441 +    public E peek() {
442 +        return peekFirst();
443 +    }
444 +
445      // *** Stack methods ***
446  
447      /**
448       * Pushes an element onto the stack represented by this deque.  In other
449 <     * words, inserts the element to the front this deque.
449 >     * words, inserts the element at the front of this deque.
450       *
451       * <p>This method is equivalent to {@link #addFirst}.
452       *
453       * @param e the element to push
454 <     * @throws NullPointerException if <tt>e</tt> is null
454 >     * @throws NullPointerException if the specified element is null
455       */
456      public void push(E e) {
457          addFirst(e);
# Line 508 | Line 464 | public class ArrayDeque<E> extends Abstr
464       * <p>This method is equivalent to {@link #removeFirst()}.
465       *
466       * @return the element at the front of this deque (which is the top
467 <     *     of the stack represented by this deque)
468 <     * @throws NoSuchElementException if this deque is empty
467 >     *         of the stack represented by this deque)
468 >     * @throws NoSuchElementException {@inheritDoc}
469       */
470      public E pop() {
471          return removeFirst();
472      }
473  
474 +    private void checkInvariants() {
475 +        assert elements[tail] == null;
476 +        assert head == tail ? elements[head] == null :
477 +            (elements[head] != null &&
478 +             elements[(tail - 1) & (elements.length - 1)] != null);
479 +        assert elements[(head - 1) & (elements.length - 1)] == null;
480 +    }
481 +
482      /**
483 <     * Remove the element at the specified position in the elements array,
484 <     * adjusting head, tail, and size as necessary.  This can result in
485 <     * motion of elements backwards or forwards in the array.
486 <     *
487 <     * <p>This method is called delete rather than remove to emphasize
488 <     * that its semantics differ from those of List.remove(int).
489 <     *
483 >     * Removes the element at the specified position in the elements array,
484 >     * adjusting head and tail as necessary.  This can result in motion of
485 >     * elements backwards or forwards in the array.
486 >     *
487 >     * <p>This method is called delete rather than remove to emphasize
488 >     * that its semantics differ from those of {@link List#remove(int)}.
489 >     *
490       * @return true if elements moved backwards
491       */
492      private boolean delete(int i) {
493 <        // Case 1: Deque doesn't wrap
494 <        // Case 2: Deque does wrap and removed element is in the head portion
495 <        if ((head < tail || tail == 0) || i >= head) {
496 <            System.arraycopy(elements, head, elements, head + 1, i - head);
497 <            elements[head] = null;
498 <            head = (head + 1) & (elements.length - 1);
493 >        checkInvariants();
494 >        final Object[] elements = this.elements;
495 >        final int mask = elements.length - 1;
496 >        final int h = head;
497 >        final int t = tail;
498 >        final int front = (i - h) & mask;
499 >        final int back  = (t - i) & mask;
500 >
501 >        // Invariant: head <= i < tail mod circularity
502 >        if (front >= ((t - h) & mask))
503 >            throw new ConcurrentModificationException();
504 >
505 >        // Optimize for least element motion
506 >        if (front < back) {
507 >            if (h <= i) {
508 >                System.arraycopy(elements, h, elements, h + 1, front);
509 >            } else { // Wrap around
510 >                System.arraycopy(elements, 0, elements, 1, i);
511 >                elements[0] = elements[mask];
512 >                System.arraycopy(elements, h, elements, h + 1, mask - h);
513 >            }
514 >            elements[h] = null;
515 >            head = (h + 1) & mask;
516              return false;
517 +        } else {
518 +            if (i < t) { // Copy the null tail as well
519 +                System.arraycopy(elements, i + 1, elements, i, back);
520 +                tail = t - 1;
521 +            } else { // Wrap around
522 +                System.arraycopy(elements, i + 1, elements, i, mask - i);
523 +                elements[mask] = elements[0];
524 +                System.arraycopy(elements, 1, elements, 0, t);
525 +                tail = (t - 1) & mask;
526 +            }
527 +            return true;
528          }
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;
529      }
530  
531      // *** Collection Methods ***
# Line 554 | Line 540 | public class ArrayDeque<E> extends Abstr
540      }
541  
542      /**
543 <     * Returns <tt>true</tt> if this collection contains no elements.<p>
543 >     * Returns {@code true} if this deque contains no elements.
544       *
545 <     * @return <tt>true</tt> if this collection contains no elements.
545 >     * @return {@code true} if this deque contains no elements
546       */
547      public boolean isEmpty() {
548          return head == tail;
# Line 567 | Line 553 | public class ArrayDeque<E> extends Abstr
553       * will be ordered from first (head) to last (tail).  This is the same
554       * order that elements would be dequeued (via successive calls to
555       * {@link #remove} or popped (via successive calls to {@link #pop}).
556 <     *
557 <     * @return an <tt>Iterator</tt> over the elements in this deque
556 >     *
557 >     * @return an iterator over the elements in this deque
558       */
559      public Iterator<E> iterator() {
560          return new DeqIterator();
561      }
562  
563 +    public Iterator<E> descendingIterator() {
564 +        return new DescendingIterator();
565 +    }
566 +
567      private class DeqIterator implements Iterator<E> {
568          /**
569           * Index of element to be returned by subsequent call to next.
# Line 597 | Line 587 | public class ArrayDeque<E> extends Abstr
587          }
588  
589          public E next() {
600            E result;
590              if (cursor == fence)
591                  throw new NoSuchElementException();
592 +            @SuppressWarnings("unchecked")
593 +            E result = (E) elements[cursor];
594              // This check doesn't catch all possible comodifications,
595              // but does catch the ones that corrupt traversal
596 <            if (tail != fence || (result = elements[cursor]) == null)
596 >            if (tail != fence || result == null)
597                  throw new ConcurrentModificationException();
598              lastRet = cursor;
599              cursor = (cursor + 1) & (elements.length - 1);
# Line 612 | Line 603 | public class ArrayDeque<E> extends Abstr
603          public void remove() {
604              if (lastRet < 0)
605                  throw new IllegalStateException();
606 <            if (delete(lastRet))
607 <                cursor--;
606 >            if (delete(lastRet)) { // if left-shifted, undo increment in next()
607 >                cursor = (cursor - 1) & (elements.length - 1);
608 >                fence = tail;
609 >            }
610 >            lastRet = -1;
611 >        }
612 >    }
613 >
614 >    private class DescendingIterator implements Iterator<E> {
615 >        /*
616 >         * This class is nearly a mirror-image of DeqIterator, using
617 >         * tail instead of head for initial cursor, and head instead of
618 >         * tail for fence.
619 >         */
620 >        private int cursor = tail;
621 >        private int fence = head;
622 >        private int lastRet = -1;
623 >
624 >        public boolean hasNext() {
625 >            return cursor != fence;
626 >        }
627 >
628 >        public E next() {
629 >            if (cursor == fence)
630 >                throw new NoSuchElementException();
631 >            cursor = (cursor - 1) & (elements.length - 1);
632 >            @SuppressWarnings("unchecked")
633 >            E result = (E) elements[cursor];
634 >            if (head != fence || result == null)
635 >                throw new ConcurrentModificationException();
636 >            lastRet = cursor;
637 >            return result;
638 >        }
639 >
640 >        public void remove() {
641 >            if (lastRet < 0)
642 >                throw new IllegalStateException();
643 >            if (!delete(lastRet)) {
644 >                cursor = (cursor + 1) & (elements.length - 1);
645 >                fence = head;
646 >            }
647              lastRet = -1;
618            fence = tail;
648          }
649      }
650  
651      /**
652 <     * Returns <tt>true</tt> if this deque contains the specified
653 <     * element.  More formally, returns <tt>true</tt> if and only if this
654 <     * deque contains at least one element <tt>e</tt> such that
626 <     * <tt>e.equals(o)</tt>.
652 >     * Returns {@code true} if this deque contains the specified element.
653 >     * More formally, returns {@code true} if and only if this deque contains
654 >     * at least one element {@code e} such that {@code o.equals(e)}.
655       *
656       * @param o object to be checked for containment in this deque
657 <     * @return <tt>true</tt> if this deque contains the specified element
657 >     * @return {@code true} if this deque contains the specified element
658       */
659      public boolean contains(Object o) {
660          if (o == null)
661              return false;
662          int mask = elements.length - 1;
663          int i = head;
664 <        E x;
664 >        Object x;
665          while ( (x = elements[i]) != null) {
666              if (o.equals(x))
667                  return true;
# Line 644 | Line 672 | public class ArrayDeque<E> extends Abstr
672  
673      /**
674       * Removes a single instance of the specified element from this deque.
675 <     * This method is equivalent to {@link #removeFirstOccurrence}.
675 >     * If the deque does not contain the element, it is unchanged.
676 >     * More formally, removes the first element {@code e} such that
677 >     * {@code o.equals(e)} (if such an element exists).
678 >     * Returns {@code true} if this deque contained the specified element
679 >     * (or equivalently, if this deque changed as a result of the call).
680 >     *
681 >     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
682       *
683 <     * @param e element to be removed from this deque, if present
684 <     * @return <tt>true</tt> if this deque contained the specified element
683 >     * @param o element to be removed from this deque, if present
684 >     * @return {@code true} if this deque contained the specified element
685       */
686 <    public boolean remove(Object e) {
687 <        return removeFirstOccurrence(e);
686 >    public boolean remove(Object o) {
687 >        return removeFirstOccurrence(o);
688      }
689  
690      /**
691       * Removes all of the elements from this deque.
692 +     * The deque will be empty after this call returns.
693       */
694      public void clear() {
695          int h = head;
# Line 666 | Line 701 | public class ArrayDeque<E> extends Abstr
701              do {
702                  elements[i] = null;
703                  i = (i + 1) & mask;
704 <            } while(i != t);
704 >            } while (i != t);
705          }
706      }
707  
708      /**
709 <     * Returns an array containing all of the elements in this list
710 <     * in the correct order.
709 >     * Returns an array containing all of the elements in this deque
710 >     * in proper sequence (from first to last element).
711 >     *
712 >     * <p>The returned array will be "safe" in that no references to it are
713 >     * maintained by this deque.  (In other words, this method must allocate
714 >     * a new array).  The caller is thus free to modify the returned array.
715       *
716 <     * @return an array containing all of the elements in this list
717 <     *         in the correct order
716 >     * <p>This method acts as bridge between array-based and collection-based
717 >     * APIs.
718 >     *
719 >     * @return an array containing all of the elements in this deque
720       */
721      public Object[] toArray() {
722 <        return copyElements(new Object[size()]);
722 >        final int head = this.head;
723 >        final int tail = this.tail;
724 >        boolean wrap = (tail < head);
725 >        int end = wrap ? tail + elements.length : tail;
726 >        Object[] a = Arrays.copyOfRange(elements, head, end);
727 >        if (wrap)
728 >            System.arraycopy(elements, 0, a, elements.length - head, tail);
729 >        return a;
730      }
731  
732      /**
733 <     * Returns an array containing all of the elements in this deque in the
734 <     * correct order; the runtime type of the returned array is that of the
735 <     * specified array.  If the deque fits in the specified array, it is
736 <     * returned therein.  Otherwise, a new array is allocated with the runtime
737 <     * type of the specified array and the size of this deque.
733 >     * Returns an array containing all of the elements in this deque in
734 >     * proper sequence (from first to last element); the runtime type of the
735 >     * returned array is that of the specified array.  If the deque fits in
736 >     * the specified array, it is returned therein.  Otherwise, a new array
737 >     * is allocated with the runtime type of the specified array and the
738 >     * size of this deque.
739 >     *
740 >     * <p>If this deque fits in the specified array with room to spare
741 >     * (i.e., the array has more elements than this deque), the element in
742 >     * the array immediately following the end of the deque is set to
743 >     * {@code null}.
744 >     *
745 >     * <p>Like the {@link #toArray()} method, this method acts as bridge between
746 >     * array-based and collection-based APIs.  Further, this method allows
747 >     * precise control over the runtime type of the output array, and may,
748 >     * under certain circumstances, be used to save allocation costs.
749 >     *
750 >     * <p>Suppose {@code x} is a deque known to contain only strings.
751 >     * The following code can be used to dump the deque into a newly
752 >     * allocated array of {@code String}:
753 >     *
754 >     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
755       *
756 <     * <p>If the deque fits in the specified array with room to spare (i.e.,
757 <     * the array has more elements than the deque), the element in the array
693 <     * immediately following the end of the collection is set to <tt>null</tt>.
756 >     * Note that {@code toArray(new Object[0])} is identical in function to
757 >     * {@code toArray()}.
758       *
759       * @param a the array into which the elements of the deque are to
760 <     *          be stored, if it is big enough; otherwise, a new array of the
761 <     *          same runtime type is allocated for this purpose
762 <     * @return an array containing the elements of the deque
763 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
764 <     *         of the runtime type of every element in this deque
760 >     *          be stored, if it is big enough; otherwise, a new array of the
761 >     *          same runtime type is allocated for this purpose
762 >     * @return an array containing all of the elements in this deque
763 >     * @throws ArrayStoreException if the runtime type of the specified array
764 >     *         is not a supertype of the runtime type of every element in
765 >     *         this deque
766 >     * @throws NullPointerException if the specified array is null
767       */
768 +    @SuppressWarnings("unchecked")
769      public <T> T[] toArray(T[] a) {
770 <        int size = size();
771 <        if (a.length < size)
772 <            a = (T[])java.lang.reflect.Array.newInstance(
773 <                    a.getClass().getComponentType(), size);
774 <        copyElements(a);
775 <        if (a.length > size)
776 <            a[size] = null;
770 >        final int head = this.head;
771 >        final int tail = this.tail;
772 >        boolean wrap = (tail < head);
773 >        int size = (tail - head) + (wrap ? elements.length : 0);
774 >        int firstLeg = size - (wrap ? tail : 0);
775 >        int len = a.length;
776 >        if (size > len) {
777 >            a = (T[]) Arrays.copyOfRange(elements, head, head + size,
778 >                                         a.getClass());
779 >        } else {
780 >            System.arraycopy(elements, head, a, 0, firstLeg);
781 >            if (size < len)
782 >                a[size] = null;
783 >        }
784 >        if (wrap)
785 >            System.arraycopy(elements, 0, a, firstLeg, tail);
786          return a;
787      }
788  
# Line 718 | Line 794 | public class ArrayDeque<E> extends Abstr
794       * @return a copy of this deque
795       */
796      public ArrayDeque<E> clone() {
797 <        try {
797 >        try {
798 >            @SuppressWarnings("unchecked")
799              ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
800 <            // 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);
800 >            result.elements = Arrays.copyOf(elements, elements.length);
801              return result;
802 <
728 <        } catch (CloneNotSupportedException e) {
802 >        } catch (CloneNotSupportedException e) {
803              throw new AssertionError();
804          }
805      }
806  
733    /**
734     * Appease the serialization gods.
735     */
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
821 <        int size = size();
750 <        s.writeInt(size);
821 >        s.writeInt(size());
822  
823          // Write out elements in order.
753        int i = head;
824          int mask = elements.length - 1;
825 <        for (int j = 0; j < size; j++) {
825 >        for (int i = head; i != tail; i = (i + 1) & mask)
826              s.writeObject(elements[i]);
757            i = (i + 1) & mask;
758        }
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 773 | 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  
847 +    Spliterator<E> spliterator() {
848 +        return new DeqSpliterator<E>(this, -1, -1);
849      }
850 +
851 +    public Stream<E> stream() {
852 +        return Streams.stream(spliterator());
853 +    }
854 +
855 +    public Stream<E> parallelStream() {
856 +        return Streams.parallelStream(spliterator());
857 +    }
858 +
859 +    static final class DeqSpliterator<E> implements Spliterator<E> {
860 +        private final ArrayDeque<E> deq;
861 +        private int fence;  // -1 until first use
862 +        private int index;  // current index, modified on traverse/split
863 +
864 +        /** Creates new spliterator covering the given array and range */
865 +        DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
866 +            this.deq = deq;
867 +            this.index = origin;
868 +            this.fence = fence;
869 +        }
870 +
871 +        private int getFence() { // force initialization
872 +            int t;
873 +            if ((t = fence) < 0) {
874 +                t = fence = deq.tail;
875 +                index = deq.head;
876 +            }
877 +            return t;
878 +        }
879 +
880 +        public DeqSpliterator<E> trySplit() {
881 +            int t = getFence(), h = index, n = deq.elements.length;
882 +            if (h != t && ((h + 1) & (n - 1)) != t) {
883 +                if (h > t)
884 +                    t += n;
885 +                int m = ((h + t) >>> 1) & (n - 1);
886 +                return new DeqSpliterator<>(deq, h, index = m);
887 +            }
888 +            return null;
889 +        }
890 +
891 +        public void forEach(Consumer<? super E> consumer) {
892 +            if (consumer == null)
893 +                throw new NullPointerException();
894 +            Object[] a = deq.elements;
895 +            int m = a.length - 1, f = getFence(), i = index;
896 +            index = f;
897 +            while (i != f) {
898 +                @SuppressWarnings("unchecked") E e = (E)a[i];
899 +                i = (i + 1) & m;
900 +                if (e == null)
901 +                    throw new ConcurrentModificationException();
902 +                consumer.accept(e);
903 +            }
904 +        }
905 +
906 +        public boolean tryAdvance(Consumer<? super E> consumer) {
907 +            if (consumer == null)
908 +                throw new NullPointerException();
909 +            Object[] a = deq.elements;
910 +            int m = a.length - 1, f = getFence(), i = index;
911 +            if (i != fence) {
912 +                @SuppressWarnings("unchecked") E e = (E)a[i];
913 +                index = (i + 1) & m;
914 +                if (e == null)
915 +                    throw new ConcurrentModificationException();
916 +                consumer.accept(e);
917 +                return true;
918 +            }
919 +            return false;
920 +        }
921 +
922 +        public long estimateSize() {
923 +            int n = getFence() - index;
924 +            if (n < 0)
925 +                n += deq.elements.length;
926 +            return (long) n;
927 +        }
928 +
929 +        @Override
930 +        public int characteristics() {
931 +            return Spliterator.ORDERED | Spliterator.SIZED |
932 +                Spliterator.NONNULL | Spliterator.SUBSIZED;
933 +        }
934 +    }
935 +
936   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines