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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines