ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.98
Committed: Sat Oct 29 22:47:55 2016 UTC (7 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.97: +11 -15 lines
Log Message:
null actions should throw NPE even when nothing to do

File Contents

# User Rev Content
1 dl 1.1 /*
2 dl 1.47 * Written by Josh Bloch of Google Inc. and released to the public domain,
3     * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
4 dl 1.1 */
5    
6     package java.util;
7 jsr166 1.61
8 dl 1.47 import java.io.Serializable;
9     import java.util.function.Consumer;
10 jsr166 1.75 import java.util.function.Predicate;
11     import java.util.function.UnaryOperator;
12 dl 1.1
13     /**
14     * Resizable-array implementation of the {@link Deque} interface. Array
15     * deques have no capacity restrictions; they grow as necessary to support
16     * usage. They are not thread-safe; in the absence of external
17     * synchronization, they do not support concurrent access by multiple threads.
18     * Null elements are prohibited. This class is likely to be faster than
19 dl 1.2 * {@link Stack} when used as a stack, and faster than {@link LinkedList}
20 dl 1.1 * when used as a queue.
21     *
22 jsr166 1.43 * <p>Most {@code ArrayDeque} operations run in amortized constant time.
23 jsr166 1.51 * Exceptions include
24     * {@link #remove(Object) remove},
25     * {@link #removeFirstOccurrence removeFirstOccurrence},
26     * {@link #removeLastOccurrence removeLastOccurrence},
27     * {@link #contains contains},
28     * {@link #iterator iterator.remove()},
29     * and the bulk operations, all of which run in linear time.
30 dl 1.41 *
31 jsr166 1.51 * <p>The iterators returned by this class's {@link #iterator() iterator}
32     * method are <em>fail-fast</em>: If the deque is modified at any time after
33     * the iterator is created, in any way except through the iterator's own
34     * {@code remove} method, the iterator will generally throw a {@link
35 jsr166 1.7 * ConcurrentModificationException}. Thus, in the face of concurrent
36     * modification, the iterator fails quickly and cleanly, rather than risking
37     * arbitrary, non-deterministic behavior at an undetermined time in the
38     * future.
39 dl 1.1 *
40     * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
41     * as it is, generally speaking, impossible to make any hard guarantees in the
42     * presence of unsynchronized concurrent modification. Fail-fast iterators
43 jsr166 1.43 * throw {@code ConcurrentModificationException} on a best-effort basis.
44 dl 1.1 * Therefore, it would be wrong to write a program that depended on this
45     * exception for its correctness: <i>the fail-fast behavior of iterators
46     * should be used only to detect bugs.</i>
47     *
48     * <p>This class and its iterator implement all of the
49 jsr166 1.9 * <em>optional</em> methods of the {@link Collection} and {@link
50     * Iterator} interfaces.
51     *
52     * <p>This class is a member of the
53 jsr166 1.29 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
54 jsr166 1.9 * Java Collections Framework</a>.
55 dl 1.1 *
56     * @author Josh Bloch and Doug Lea
57 jsr166 1.74 * @param <E> the type of elements held in this deque
58 dl 1.1 * @since 1.6
59     */
60     public class ArrayDeque<E> extends AbstractCollection<E>
61 dl 1.47 implements Deque<E>, Cloneable, Serializable
62 dl 1.1 {
63     /**
64 dl 1.4 * The array in which the elements of the deque are stored.
65 jsr166 1.75 * We guarantee that all array cells not holding deque elements
66     * are always null.
67 dl 1.1 */
68 jsr166 1.75 transient Object[] elements;
69 dl 1.1
70     /**
71     * The index of the element at the head of the deque (which is the
72     * element that would be removed by remove() or pop()); or an
73 jsr166 1.75 * arbitrary number 0 <= head < elements.length if the deque is empty.
74 dl 1.1 */
75 dl 1.41 transient int head;
76 dl 1.1
77 jsr166 1.75 /** Number of elements in this collection. */
78     transient int size;
79    
80 dl 1.1 /**
81 jsr166 1.75 * The maximum size of array to allocate.
82     * Some VMs reserve some header words in an array.
83     * Attempts to allocate larger arrays may result in
84     * OutOfMemoryError: Requested array size exceeds VM limit
85 dl 1.1 */
86 jsr166 1.75 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
87 dl 1.1
88     /**
89 jsr166 1.75 * Increases the capacity of this deque by at least the given amount.
90     *
91     * @param needed the required minimum extra capacity; must be positive
92 dl 1.1 */
93 jsr166 1.75 private void grow(int needed) {
94     // overflow-conscious code
95     // checkInvariants();
96 jsr166 1.91 final int oldCapacity = elements.length;
97 jsr166 1.75 int newCapacity;
98     // Double size if small; else grow by 50%
99     int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
100     if (jump < needed
101     || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
102     newCapacity = newCapacity(needed, jump);
103     elements = Arrays.copyOf(elements, newCapacity);
104     if (oldCapacity - head < size) {
105     // wrap around; slide first leg forward to end of array
106     int newSpace = newCapacity - oldCapacity;
107     System.arraycopy(elements, head,
108     elements, head + newSpace,
109     oldCapacity - head);
110     Arrays.fill(elements, head, head + newSpace, null);
111     head += newSpace;
112     }
113     // checkInvariants();
114     }
115 dl 1.1
116 jsr166 1.75 /** Capacity calculation for edge conditions, especially overflow. */
117     private int newCapacity(int needed, int jump) {
118 jsr166 1.91 final int oldCapacity = elements.length, minCapacity;
119 jsr166 1.75 if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
120     if (minCapacity < 0)
121     throw new IllegalStateException("Sorry, deque too big");
122     return Integer.MAX_VALUE;
123     }
124     if (needed > jump)
125     return minCapacity;
126     return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
127     ? oldCapacity + jump
128     : MAX_ARRAY_SIZE;
129     }
130 dl 1.1
131     /**
132 jsr166 1.75 * Increases the internal storage of this collection, if necessary,
133     * to ensure that it can hold at least the given number of elements.
134 dl 1.1 *
135 jsr166 1.75 * @param minCapacity the desired minimum capacity
136 jsr166 1.80 * @since TBD
137 dl 1.1 */
138 jsr166 1.80 /* public */ void ensureCapacity(int minCapacity) {
139 jsr166 1.75 if (minCapacity > elements.length)
140     grow(minCapacity - elements.length);
141     // checkInvariants();
142 dl 1.1 }
143    
144     /**
145 jsr166 1.75 * Minimizes the internal storage of this collection.
146 jsr166 1.80 *
147     * @since TBD
148 dl 1.1 */
149 jsr166 1.80 /* public */ void trimToSize() {
150 jsr166 1.75 if (size < elements.length) {
151     elements = toArray();
152     head = 0;
153     }
154     // checkInvariants();
155 dl 1.1 }
156    
157     /**
158 dl 1.4 * Constructs an empty array deque with an initial capacity
159 dl 1.1 * sufficient to hold 16 elements.
160     */
161     public ArrayDeque() {
162 jsr166 1.34 elements = new Object[16];
163 dl 1.1 }
164    
165     /**
166     * Constructs an empty array deque with an initial capacity
167     * sufficient to hold the specified number of elements.
168     *
169 jsr166 1.75 * @param numElements lower bound on initial capacity of the deque
170 dl 1.1 */
171     public ArrayDeque(int numElements) {
172 jsr166 1.75 elements = new Object[numElements];
173 dl 1.1 }
174    
175     /**
176     * Constructs a deque containing the elements of the specified
177     * collection, in the order they are returned by the collection's
178     * iterator. (The first element returned by the collection's
179     * iterator becomes the first element, or <i>front</i> of the
180     * deque.)
181     *
182     * @param c the collection whose elements are to be placed into the deque
183     * @throws NullPointerException if the specified collection is null
184     */
185     public ArrayDeque(Collection<? extends E> c) {
186 jsr166 1.95 Object[] es = c.toArray();
187 jsr166 1.75 // defend against c.toArray (incorrectly) not returning Object[]
188     // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
189 jsr166 1.95 if (es.getClass() != Object[].class)
190     es = Arrays.copyOf(es, es.length, Object[].class);
191     for (Object obj : es)
192 jsr166 1.75 Objects.requireNonNull(obj);
193 jsr166 1.95 this.elements = es;
194     this.size = es.length;
195 jsr166 1.75 }
196    
197     /**
198 jsr166 1.79 * Increments i, mod modulus.
199     * Precondition and postcondition: 0 <= i < modulus.
200 jsr166 1.75 */
201 jsr166 1.79 static final int inc(int i, int modulus) {
202 jsr166 1.89 if (++i >= modulus) i = 0;
203 jsr166 1.79 return i;
204 jsr166 1.75 }
205    
206     /**
207 jsr166 1.79 * Decrements i, mod modulus.
208     * Precondition and postcondition: 0 <= i < modulus.
209 jsr166 1.75 */
210 jsr166 1.79 static final int dec(int i, int modulus) {
211 jsr166 1.89 if (--i < 0) i = modulus - 1;
212 jsr166 1.75 return i;
213     }
214    
215     /**
216 jsr166 1.79 * Adds i and j, mod modulus.
217     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
218 jsr166 1.75 */
219 jsr166 1.79 static final int add(int i, int j, int modulus) {
220     if ((i += j) - modulus >= 0) i -= modulus;
221 jsr166 1.75 return i;
222     }
223    
224     /**
225 jsr166 1.79 * Returns the array index of the last element.
226     * May return invalid index -1 if there are no elements.
227 jsr166 1.75 */
228 jsr166 1.79 final int tail() {
229     return add(head, size - 1, elements.length);
230 jsr166 1.75 }
231    
232     /**
233     * Returns element at array index i.
234     */
235     @SuppressWarnings("unchecked")
236 jsr166 1.88 private E elementAt(int i) {
237 jsr166 1.75 return (E) elements[i];
238     }
239    
240     /**
241     * A version of elementAt that checks for null elements.
242     * This check doesn't catch all possible comodifications,
243 jsr166 1.92 * but does catch ones that corrupt traversal. It's a little
244     * surprising that javac allows this abuse of generics.
245 jsr166 1.75 */
246 jsr166 1.96 static final <E> E nonNullElementAt(Object[] es, int i) {
247     @SuppressWarnings("unchecked") E e = (E) es[i];
248 jsr166 1.75 if (e == null)
249     throw new ConcurrentModificationException();
250     return e;
251 dl 1.1 }
252    
253     // The main insertion and extraction methods are addFirst,
254     // addLast, pollFirst, pollLast. The other methods are defined in
255     // terms of these.
256    
257     /**
258 dl 1.5 * Inserts the specified element at the front of this deque.
259 dl 1.1 *
260 jsr166 1.9 * @param e the element to add
261     * @throws NullPointerException if the specified element is null
262 dl 1.1 */
263     public void addFirst(E e) {
264 jsr166 1.75 // checkInvariants();
265     Objects.requireNonNull(e);
266 jsr166 1.95 Object[] es;
267 jsr166 1.89 int capacity, h;
268     final int s;
269 jsr166 1.95 if ((s = size) == (capacity = (es = elements).length)) {
270 jsr166 1.89 grow(1);
271 jsr166 1.95 capacity = (es = elements).length;
272 jsr166 1.89 }
273     if ((h = head - 1) < 0) h = capacity - 1;
274 jsr166 1.95 es[head = h] = e;
275 jsr166 1.75 size = s + 1;
276 jsr166 1.83 // checkInvariants();
277 dl 1.1 }
278    
279     /**
280 dl 1.6 * Inserts the specified element at the end of this deque.
281 jsr166 1.14 *
282     * <p>This method is equivalent to {@link #add}.
283 dl 1.1 *
284 jsr166 1.9 * @param e the element to add
285     * @throws NullPointerException if the specified element is null
286 dl 1.1 */
287     public void addLast(E e) {
288 jsr166 1.75 // checkInvariants();
289     Objects.requireNonNull(e);
290 jsr166 1.95 Object[] es;
291 jsr166 1.89 int capacity;
292     final int s;
293 jsr166 1.95 if ((s = size) == (capacity = (es = elements).length)) {
294 jsr166 1.89 grow(1);
295 jsr166 1.95 capacity = (es = elements).length;
296 jsr166 1.89 }
297 jsr166 1.95 es[add(head, s, capacity)] = e;
298 jsr166 1.75 size = s + 1;
299 jsr166 1.83 // checkInvariants();
300 jsr166 1.75 }
301    
302     /**
303     * Adds all of the elements in the specified collection at the end
304     * of this deque, as if by calling {@link #addLast} on each one,
305     * in the order that they are returned by the collection's
306     * iterator.
307     *
308     * @param c the elements to be inserted into this deque
309     * @return {@code true} if this deque changed as a result of the call
310     * @throws NullPointerException if the specified collection or any
311     * of its elements are null
312     */
313     public boolean addAll(Collection<? extends E> c) {
314 jsr166 1.87 final int s = size, needed = c.size() - (elements.length - s);
315     if (needed > 0)
316     grow(needed);
317     c.forEach((e) -> addLast(e));
318 jsr166 1.75 // checkInvariants();
319 jsr166 1.87 return size > s;
320 dl 1.1 }
321    
322     /**
323 dl 1.5 * Inserts the specified element at the front of this deque.
324 dl 1.1 *
325 jsr166 1.9 * @param e the element to add
326 jsr166 1.40 * @return {@code true} (as specified by {@link Deque#offerFirst})
327 jsr166 1.9 * @throws NullPointerException if the specified element is null
328 dl 1.1 */
329     public boolean offerFirst(E e) {
330     addFirst(e);
331     return true;
332     }
333    
334     /**
335 dl 1.6 * Inserts the specified element at the end of this deque.
336 dl 1.1 *
337 jsr166 1.9 * @param e the element to add
338 jsr166 1.40 * @return {@code true} (as specified by {@link Deque#offerLast})
339 jsr166 1.9 * @throws NullPointerException if the specified element is null
340 dl 1.1 */
341     public boolean offerLast(E e) {
342     addLast(e);
343     return true;
344     }
345    
346     /**
347 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
348 dl 1.1 */
349     public E removeFirst() {
350 jsr166 1.75 // checkInvariants();
351 jsr166 1.84 E e = pollFirst();
352     if (e == null)
353 dl 1.1 throw new NoSuchElementException();
354 jsr166 1.84 return e;
355 dl 1.1 }
356    
357     /**
358 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
359 dl 1.1 */
360     public E removeLast() {
361 jsr166 1.75 // checkInvariants();
362 jsr166 1.84 E e = pollLast();
363     if (e == null)
364 dl 1.1 throw new NoSuchElementException();
365 jsr166 1.84 return e;
366 dl 1.1 }
367    
368 jsr166 1.9 public E pollFirst() {
369 jsr166 1.75 // checkInvariants();
370 jsr166 1.89 int s, h;
371 jsr166 1.91 if ((s = size) <= 0)
372 jsr166 1.75 return null;
373 jsr166 1.66 final Object[] elements = this.elements;
374 jsr166 1.75 @SuppressWarnings("unchecked") E e = (E) elements[h = head];
375     elements[h] = null;
376 jsr166 1.89 if (++h >= elements.length) h = 0;
377     head = h;
378 jsr166 1.75 size = s - 1;
379     return e;
380 dl 1.1 }
381    
382 jsr166 1.9 public E pollLast() {
383 jsr166 1.75 // checkInvariants();
384     final int s, tail;
385 jsr166 1.91 if ((s = size) <= 0)
386 jsr166 1.75 return null;
387 jsr166 1.66 final Object[] elements = this.elements;
388 jsr166 1.37 @SuppressWarnings("unchecked")
389 jsr166 1.75 E e = (E) elements[tail = add(head, s - 1, elements.length)];
390     elements[tail] = null;
391     size = s - 1;
392     return e;
393 dl 1.1 }
394    
395     /**
396 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
397 dl 1.1 */
398     public E getFirst() {
399 jsr166 1.75 // checkInvariants();
400 jsr166 1.91 if (size <= 0) throw new NoSuchElementException();
401 jsr166 1.75 return elementAt(head);
402 dl 1.1 }
403    
404     /**
405 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
406 dl 1.1 */
407 jsr166 1.91 @SuppressWarnings("unchecked")
408 dl 1.1 public E getLast() {
409 jsr166 1.75 // checkInvariants();
410 jsr166 1.91 final int s;
411     if ((s = size) <= 0) throw new NoSuchElementException();
412     final Object[] elements = this.elements;
413     return (E) elements[add(head, s - 1, elements.length)];
414 dl 1.1 }
415    
416 jsr166 1.9 public E peekFirst() {
417 jsr166 1.75 // checkInvariants();
418 jsr166 1.91 return (size <= 0) ? null : elementAt(head);
419 jsr166 1.9 }
420    
421 jsr166 1.91 @SuppressWarnings("unchecked")
422 jsr166 1.9 public E peekLast() {
423 jsr166 1.75 // checkInvariants();
424 jsr166 1.91 final int s;
425     if ((s = size) <= 0) return null;
426     final Object[] elements = this.elements;
427     return (E) elements[add(head, s - 1, elements.length)];
428 jsr166 1.9 }
429    
430 dl 1.1 /**
431     * Removes the first occurrence of the specified element in this
432 jsr166 1.9 * deque (when traversing the deque from head to tail).
433     * If the deque does not contain the element, it is unchanged.
434 jsr166 1.40 * More formally, removes the first element {@code e} such that
435     * {@code o.equals(e)} (if such an element exists).
436     * Returns {@code true} if this deque contained the specified element
437 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
438 dl 1.1 *
439 dl 1.5 * @param o element to be removed from this deque, if present
440 jsr166 1.40 * @return {@code true} if the deque contained the specified element
441 dl 1.1 */
442 dl 1.5 public boolean removeFirstOccurrence(Object o) {
443 jsr166 1.58 if (o != null) {
444 jsr166 1.75 final Object[] elements = this.elements;
445     final int capacity = elements.length;
446 jsr166 1.92 int i, end, to, todo;
447     todo = (end = (i = head) + size)
448 jsr166 1.89 - (to = (capacity - end >= 0) ? end : capacity);
449 jsr166 1.94 for (;; to = todo, i = 0, todo = 0) {
450 jsr166 1.92 for (; i < to; i++)
451 jsr166 1.89 if (o.equals(elements[i])) {
452     delete(i);
453     return true;
454     }
455 jsr166 1.90 if (todo == 0) break;
456 dl 1.1 }
457     }
458     return false;
459     }
460    
461     /**
462     * Removes the last occurrence of the specified element in this
463 jsr166 1.9 * deque (when traversing the deque from head to tail).
464     * If the deque does not contain the element, it is unchanged.
465 jsr166 1.40 * More formally, removes the last element {@code e} such that
466     * {@code o.equals(e)} (if such an element exists).
467     * Returns {@code true} if this deque contained the specified element
468 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
469 dl 1.1 *
470 dl 1.5 * @param o element to be removed from this deque, if present
471 jsr166 1.40 * @return {@code true} if the deque contained the specified element
472 dl 1.1 */
473 dl 1.5 public boolean removeLastOccurrence(Object o) {
474 jsr166 1.59 if (o != null) {
475 jsr166 1.75 final Object[] elements = this.elements;
476     final int capacity = elements.length;
477 jsr166 1.92 int i, to, end, todo;
478     todo = (to = ((end = (i = tail()) - size) >= -1) ? end : -1) - end;
479 jsr166 1.94 for (;; to = (i = capacity - 1) - todo, todo = 0) {
480 jsr166 1.92 for (; i > to; i--)
481 jsr166 1.89 if (o.equals(elements[i])) {
482     delete(i);
483     return true;
484     }
485 jsr166 1.90 if (todo == 0) break;
486 dl 1.1 }
487     }
488     return false;
489     }
490    
491     // *** Queue methods ***
492    
493     /**
494 dl 1.6 * Inserts the specified element at the end of this deque.
495 dl 1.1 *
496     * <p>This method is equivalent to {@link #addLast}.
497     *
498 jsr166 1.9 * @param e the element to add
499 jsr166 1.40 * @return {@code true} (as specified by {@link Collection#add})
500 jsr166 1.9 * @throws NullPointerException if the specified element is null
501 dl 1.1 */
502     public boolean add(E e) {
503     addLast(e);
504     return true;
505     }
506    
507     /**
508 jsr166 1.9 * Inserts the specified element at the end of this deque.
509 dl 1.1 *
510 jsr166 1.9 * <p>This method is equivalent to {@link #offerLast}.
511 dl 1.1 *
512 jsr166 1.9 * @param e the element to add
513 jsr166 1.40 * @return {@code true} (as specified by {@link Queue#offer})
514 jsr166 1.9 * @throws NullPointerException if the specified element is null
515 dl 1.1 */
516 jsr166 1.9 public boolean offer(E e) {
517     return offerLast(e);
518 dl 1.1 }
519    
520     /**
521     * Retrieves and removes the head of the queue represented by this deque.
522 jsr166 1.15 *
523     * This method differs from {@link #poll poll} only in that it throws an
524 jsr166 1.9 * exception if this deque is empty.
525 dl 1.1 *
526     * <p>This method is equivalent to {@link #removeFirst}.
527     *
528     * @return the head of the queue represented by this deque
529 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
530 dl 1.1 */
531     public E remove() {
532     return removeFirst();
533     }
534    
535     /**
536 jsr166 1.9 * Retrieves and removes the head of the queue represented by this deque
537     * (in other words, the first element of this deque), or returns
538 jsr166 1.40 * {@code null} if this deque is empty.
539 dl 1.1 *
540 jsr166 1.9 * <p>This method is equivalent to {@link #pollFirst}.
541 dl 1.1 *
542     * @return the head of the queue represented by this deque, or
543 jsr166 1.40 * {@code null} if this deque is empty
544 dl 1.1 */
545 jsr166 1.9 public E poll() {
546     return pollFirst();
547 dl 1.1 }
548    
549     /**
550     * Retrieves, but does not remove, the head of the queue represented by
551 jsr166 1.15 * this deque. This method differs from {@link #peek peek} only in
552     * that it throws an exception if this deque is empty.
553 dl 1.1 *
554 jsr166 1.8 * <p>This method is equivalent to {@link #getFirst}.
555 dl 1.1 *
556     * @return the head of the queue represented by this deque
557 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
558 dl 1.1 */
559     public E element() {
560     return getFirst();
561     }
562    
563 jsr166 1.9 /**
564     * Retrieves, but does not remove, the head of the queue represented by
565 jsr166 1.40 * this deque, or returns {@code null} if this deque is empty.
566 jsr166 1.9 *
567     * <p>This method is equivalent to {@link #peekFirst}.
568     *
569     * @return the head of the queue represented by this deque, or
570 jsr166 1.40 * {@code null} if this deque is empty
571 jsr166 1.9 */
572     public E peek() {
573     return peekFirst();
574     }
575    
576 dl 1.1 // *** Stack methods ***
577    
578     /**
579     * Pushes an element onto the stack represented by this deque. In other
580 dl 1.5 * words, inserts the element at the front of this deque.
581 dl 1.1 *
582     * <p>This method is equivalent to {@link #addFirst}.
583     *
584     * @param e the element to push
585 jsr166 1.9 * @throws NullPointerException if the specified element is null
586 dl 1.1 */
587     public void push(E e) {
588     addFirst(e);
589     }
590    
591     /**
592     * Pops an element from the stack represented by this deque. In other
593 dl 1.2 * words, removes and returns the first element of this deque.
594 dl 1.1 *
595     * <p>This method is equivalent to {@link #removeFirst()}.
596     *
597     * @return the element at the front of this deque (which is the top
598 jsr166 1.9 * of the stack represented by this deque)
599     * @throws NoSuchElementException {@inheritDoc}
600 dl 1.1 */
601     public E pop() {
602     return removeFirst();
603     }
604    
605     /**
606 jsr166 1.75 * Removes the element at the specified position in the elements array.
607     * This can result in forward or backwards motion of array elements.
608     * We optimize for least element motion.
609 dl 1.1 *
610 dl 1.5 * <p>This method is called delete rather than remove to emphasize
611 jsr166 1.9 * that its semantics differ from those of {@link List#remove(int)}.
612 dl 1.5 *
613 dl 1.1 * @return true if elements moved backwards
614     */
615 jsr166 1.71 boolean delete(int i) {
616 jsr166 1.75 // checkInvariants();
617 jsr166 1.34 final Object[] elements = this.elements;
618 jsr166 1.75 final int capacity = elements.length;
619 jsr166 1.30 final int h = head;
620 jsr166 1.75 int front; // number of elements before to-be-deleted elt
621     if ((front = i - h) < 0) front += capacity;
622     final int back = size - front - 1; // number of elements after
623 jsr166 1.30 if (front < back) {
624 jsr166 1.75 // move front elements forwards
625 jsr166 1.30 if (h <= i) {
626     System.arraycopy(elements, h, elements, h + 1, front);
627     } else { // Wrap around
628     System.arraycopy(elements, 0, elements, 1, i);
629 jsr166 1.75 elements[0] = elements[capacity - 1];
630     System.arraycopy(elements, h, elements, h + 1, front - (i + 1));
631 jsr166 1.30 }
632     elements[h] = null;
633 jsr166 1.89 if ((head = (h + 1)) >= capacity) head = 0;
634 jsr166 1.75 size--;
635     // checkInvariants();
636 jsr166 1.30 return false;
637     } else {
638 jsr166 1.75 // move back elements backwards
639     int tail = tail();
640     if (i <= tail) {
641 jsr166 1.30 System.arraycopy(elements, i + 1, elements, i, back);
642     } else { // Wrap around
643 jsr166 1.75 int firstLeg = capacity - (i + 1);
644     System.arraycopy(elements, i + 1, elements, i, firstLeg);
645     elements[capacity - 1] = elements[0];
646     System.arraycopy(elements, 1, elements, 0, back - firstLeg - 1);
647 jsr166 1.30 }
648 jsr166 1.75 elements[tail] = null;
649     size--;
650     // checkInvariants();
651 jsr166 1.30 return true;
652     }
653 dl 1.23 }
654    
655 dl 1.1 // *** Collection Methods ***
656    
657     /**
658     * Returns the number of elements in this deque.
659     *
660     * @return the number of elements in this deque
661     */
662     public int size() {
663 jsr166 1.75 return size;
664 dl 1.1 }
665    
666     /**
667 jsr166 1.40 * Returns {@code true} if this deque contains no elements.
668 dl 1.1 *
669 jsr166 1.40 * @return {@code true} if this deque contains no elements
670 dl 1.1 */
671     public boolean isEmpty() {
672 jsr166 1.75 return size == 0;
673 dl 1.1 }
674    
675     /**
676     * Returns an iterator over the elements in this deque. The elements
677     * will be ordered from first (head) to last (tail). This is the same
678     * order that elements would be dequeued (via successive calls to
679     * {@link #remove} or popped (via successive calls to {@link #pop}).
680 dl 1.5 *
681 jsr166 1.18 * @return an iterator over the elements in this deque
682 dl 1.1 */
683     public Iterator<E> iterator() {
684     return new DeqIterator();
685     }
686    
687 dl 1.16 public Iterator<E> descendingIterator() {
688     return new DescendingIterator();
689     }
690    
691 dl 1.1 private class DeqIterator implements Iterator<E> {
692 jsr166 1.75 /** Index of element to be returned by subsequent call to next. */
693     int cursor;
694 dl 1.1
695 jsr166 1.75 /** Number of elements yet to be returned. */
696     int remaining = size;
697 dl 1.1
698     /**
699     * Index of element returned by most recent call to next.
700     * Reset to -1 if element is deleted by a call to remove.
701     */
702 jsr166 1.75 int lastRet = -1;
703 dl 1.1
704 jsr166 1.75 DeqIterator() { cursor = head; }
705    
706     public final boolean hasNext() {
707     return remaining > 0;
708     }
709    
710 jsr166 1.81 public E next() {
711 jsr166 1.91 if (remaining <= 0)
712 dl 1.1 throw new NoSuchElementException();
713 jsr166 1.89 final Object[] elements = ArrayDeque.this.elements;
714 jsr166 1.92 E e = nonNullElementAt(elements, cursor);
715 dl 1.1 lastRet = cursor;
716 jsr166 1.89 if (++cursor >= elements.length) cursor = 0;
717 jsr166 1.75 remaining--;
718     return e;
719 dl 1.1 }
720    
721 jsr166 1.81 void postDelete(boolean leftShifted) {
722     if (leftShifted)
723 jsr166 1.89 if (--cursor < 0) cursor = elements.length - 1;
724 jsr166 1.81 }
725    
726 jsr166 1.75 public final void remove() {
727 dl 1.1 if (lastRet < 0)
728     throw new IllegalStateException();
729 jsr166 1.81 postDelete(delete(lastRet));
730 dl 1.1 lastRet = -1;
731     }
732 jsr166 1.68
733 jsr166 1.81 public void forEachRemaining(Consumer<? super E> action) {
734 jsr166 1.98 Objects.requireNonNull(action);
735 jsr166 1.91 final int k;
736 jsr166 1.89 if ((k = remaining) > 0) {
737     remaining = 0;
738     ArrayDeque.forEachRemaining(action, elements, cursor, k);
739     if ((lastRet = cursor + k - 1) >= elements.length)
740     lastRet -= elements.length;
741     }
742 jsr166 1.68 }
743 dl 1.1 }
744    
745 jsr166 1.75 private class DescendingIterator extends DeqIterator {
746     DescendingIterator() { cursor = tail(); }
747    
748 jsr166 1.81 public final E next() {
749 jsr166 1.91 if (remaining <= 0)
750 jsr166 1.81 throw new NoSuchElementException();
751 jsr166 1.89 final Object[] elements = ArrayDeque.this.elements;
752 jsr166 1.92 E e = nonNullElementAt(elements, cursor);
753 jsr166 1.81 lastRet = cursor;
754 jsr166 1.89 if (--cursor < 0) cursor = elements.length - 1;
755 jsr166 1.81 remaining--;
756     return e;
757 jsr166 1.75 }
758    
759 jsr166 1.81 void postDelete(boolean leftShifted) {
760     if (!leftShifted)
761 jsr166 1.89 if (++cursor >= elements.length) cursor = 0;
762 jsr166 1.81 }
763    
764     public final void forEachRemaining(Consumer<? super E> action) {
765 jsr166 1.98 Objects.requireNonNull(action);
766 jsr166 1.91 final int k;
767 jsr166 1.89 if ((k = remaining) > 0) {
768     remaining = 0;
769 jsr166 1.98 final Object[] elements = ArrayDeque.this.elements;
770     int i, end, to, todo;
771     todo = (to = ((end = (i = cursor) - k) >= -1) ? end : -1) - end;
772     for (;; to = (i = elements.length - 1) - todo, todo = 0) {
773     for (; i > to; i--)
774     action.accept(nonNullElementAt(elements, i));
775     if (todo == 0) break;
776     }
777 jsr166 1.89 if ((lastRet = cursor - (k - 1)) < 0)
778     lastRet += elements.length;
779     }
780 jsr166 1.75 }
781     }
782    
783 jsr166 1.52 /**
784 jsr166 1.75 * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
785     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
786     * deque.
787     *
788     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
789     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
790     * {@link Spliterator#NONNULL}. Overriding implementations should document
791     * the reporting of additional characteristic values.
792     *
793     * @return a {@code Spliterator} over the elements in this deque
794     * @since 1.8
795 jsr166 1.52 */
796 jsr166 1.75 public Spliterator<E> spliterator() {
797 jsr166 1.76 return new ArrayDequeSpliterator();
798 jsr166 1.75 }
799    
800     final class ArrayDequeSpliterator implements Spliterator<E> {
801     private int cursor;
802 jsr166 1.76 private int remaining; // -1 until late-binding first use
803 jsr166 1.75
804 jsr166 1.76 /** Constructs late-binding spliterator over all elements. */
805     ArrayDequeSpliterator() {
806     this.remaining = -1;
807     }
808    
809     /** Constructs spliterator over the given slice. */
810 jsr166 1.75 ArrayDequeSpliterator(int cursor, int count) {
811     this.cursor = cursor;
812     this.remaining = count;
813     }
814    
815 jsr166 1.76 /** Ensures late-binding initialization; then returns remaining. */
816     private int remaining() {
817     if (remaining < 0) {
818     cursor = head;
819     remaining = size;
820     }
821     return remaining;
822     }
823    
824 jsr166 1.75 public ArrayDequeSpliterator trySplit() {
825 jsr166 1.77 final int mid;
826     if ((mid = remaining() >> 1) > 0) {
827 jsr166 1.75 int oldCursor = cursor;
828 jsr166 1.76 cursor = add(cursor, mid, elements.length);
829 jsr166 1.75 remaining -= mid;
830     return new ArrayDequeSpliterator(oldCursor, mid);
831     }
832     return null;
833     }
834 dl 1.16
835 jsr166 1.75 public void forEachRemaining(Consumer<? super E> action) {
836 jsr166 1.98 Objects.requireNonNull(action);
837 jsr166 1.91 final int k = remaining(); // side effect!
838 jsr166 1.77 remaining = 0;
839 jsr166 1.89 ArrayDeque.forEachRemaining(action, elements, cursor, k);
840 dl 1.16 }
841    
842 jsr166 1.75 public boolean tryAdvance(Consumer<? super E> action) {
843     Objects.requireNonNull(action);
844 jsr166 1.91 final int k;
845     if ((k = remaining()) <= 0)
846 jsr166 1.75 return false;
847 jsr166 1.92 action.accept(nonNullElementAt(elements, cursor));
848 jsr166 1.89 if (++cursor >= elements.length) cursor = 0;
849 jsr166 1.91 remaining = k - 1;
850 jsr166 1.75 return true;
851     }
852    
853     public long estimateSize() {
854 jsr166 1.76 return remaining();
855 jsr166 1.75 }
856    
857     public int characteristics() {
858     return Spliterator.NONNULL
859     | Spliterator.ORDERED
860     | Spliterator.SIZED
861     | Spliterator.SUBSIZED;
862 dl 1.16 }
863 jsr166 1.75 }
864 dl 1.16
865 jsr166 1.89 @SuppressWarnings("unchecked")
866 jsr166 1.75 public void forEach(Consumer<? super E> action) {
867     Objects.requireNonNull(action);
868     final Object[] elements = this.elements;
869     final int capacity = elements.length;
870 jsr166 1.92 int i, end, to, todo;
871     todo = (end = (i = head) + size)
872 jsr166 1.89 - (to = (capacity - end >= 0) ? end : capacity);
873 jsr166 1.94 for (;; to = todo, i = 0, todo = 0) {
874 jsr166 1.92 for (; i < to; i++)
875 jsr166 1.89 action.accept((E) elements[i]);
876 jsr166 1.90 if (todo == 0) break;
877 jsr166 1.89 }
878 jsr166 1.75 // checkInvariants();
879     }
880    
881     /**
882 jsr166 1.92 * Calls action on remaining elements, starting at index i and
883     * traversing in ascending order. A variant of forEach that also
884     * checks for concurrent modification, for use in iterators.
885 jsr166 1.89 */
886     static <E> void forEachRemaining(
887 jsr166 1.97 Consumer<? super E> action, Object[] es, int i, int remaining) {
888     final int capacity = es.length;
889 jsr166 1.90 int end, to, todo;
890 jsr166 1.92 todo = (end = i + remaining)
891 jsr166 1.89 - (to = (capacity - end >= 0) ? end : capacity);
892 jsr166 1.94 for (;; to = todo, i = 0, todo = 0) {
893 jsr166 1.92 for (; i < to; i++)
894 jsr166 1.97 action.accept(nonNullElementAt(es, i));
895 jsr166 1.90 if (todo == 0) break;
896 jsr166 1.89 }
897     }
898    
899     /**
900 jsr166 1.75 * Replaces each element of this deque with the result of applying the
901     * operator to that element, as specified by {@link List#replaceAll}.
902     *
903     * @param operator the operator to apply to each element
904 jsr166 1.80 * @since TBD
905 jsr166 1.75 */
906 jsr166 1.80 /* public */ void replaceAll(UnaryOperator<E> operator) {
907 jsr166 1.75 Objects.requireNonNull(operator);
908     final Object[] elements = this.elements;
909     final int capacity = elements.length;
910 jsr166 1.92 int i, end, to, todo;
911     todo = (end = (i = head) + size)
912 jsr166 1.89 - (to = (capacity - end >= 0) ? end : capacity);
913 jsr166 1.94 for (;; to = todo, i = 0, todo = 0) {
914 jsr166 1.92 for (; i < to; i++)
915 jsr166 1.89 elements[i] = operator.apply(elementAt(i));
916 jsr166 1.90 if (todo == 0) break;
917 jsr166 1.89 }
918 jsr166 1.75 // checkInvariants();
919     }
920    
921     /**
922     * @throws NullPointerException {@inheritDoc}
923     */
924     public boolean removeIf(Predicate<? super E> filter) {
925     Objects.requireNonNull(filter);
926     return bulkRemove(filter);
927     }
928    
929     /**
930     * @throws NullPointerException {@inheritDoc}
931     */
932     public boolean removeAll(Collection<?> c) {
933     Objects.requireNonNull(c);
934     return bulkRemove(e -> c.contains(e));
935     }
936    
937     /**
938     * @throws NullPointerException {@inheritDoc}
939     */
940     public boolean retainAll(Collection<?> c) {
941     Objects.requireNonNull(c);
942     return bulkRemove(e -> !c.contains(e));
943     }
944    
945     /** Implementation of bulk remove methods. */
946     private boolean bulkRemove(Predicate<? super E> filter) {
947     // checkInvariants();
948     final Object[] elements = this.elements;
949     final int capacity = elements.length;
950     int i = head, j = i, remaining = size, deleted = 0;
951     try {
952 jsr166 1.89 for (; remaining > 0; remaining--) {
953 jsr166 1.75 @SuppressWarnings("unchecked") E e = (E) elements[i];
954     if (filter.test(e))
955     deleted++;
956     else {
957     if (j != i)
958     elements[j] = e;
959 jsr166 1.89 if (++j >= capacity) j = 0;
960 jsr166 1.75 }
961 jsr166 1.89 if (++i >= capacity) i = 0;
962 jsr166 1.30 }
963 jsr166 1.75 return deleted > 0;
964     } catch (Throwable ex) {
965 jsr166 1.78 if (deleted > 0)
966 jsr166 1.89 for (; remaining > 0; remaining--) {
967 jsr166 1.78 elements[j] = elements[i];
968 jsr166 1.89 if (++i >= capacity) i = 0;
969     if (++j >= capacity) j = 0;
970     }
971 jsr166 1.75 throw ex;
972     } finally {
973     size -= deleted;
974 jsr166 1.89 clearSlice(elements, j, deleted);
975 jsr166 1.75 // checkInvariants();
976 dl 1.16 }
977     }
978    
979 dl 1.1 /**
980 jsr166 1.40 * Returns {@code true} if this deque contains the specified element.
981     * More formally, returns {@code true} if and only if this deque contains
982     * at least one element {@code e} such that {@code o.equals(e)}.
983 dl 1.1 *
984     * @param o object to be checked for containment in this deque
985 jsr166 1.40 * @return {@code true} if this deque contains the specified element
986 dl 1.1 */
987     public boolean contains(Object o) {
988 jsr166 1.58 if (o != null) {
989 jsr166 1.75 final Object[] elements = this.elements;
990     final int capacity = elements.length;
991 jsr166 1.92 int i, end, to, todo;
992     todo = (end = (i = head) + size)
993 jsr166 1.89 - (to = (capacity - end >= 0) ? end : capacity);
994 jsr166 1.94 for (;; to = todo, i = 0, todo = 0) {
995 jsr166 1.92 for (; i < to; i++)
996 jsr166 1.89 if (o.equals(elements[i]))
997     return true;
998 jsr166 1.90 if (todo == 0) break;
999 jsr166 1.89 }
1000 dl 1.1 }
1001     return false;
1002     }
1003    
1004     /**
1005     * Removes a single instance of the specified element from this deque.
1006 jsr166 1.9 * If the deque does not contain the element, it is unchanged.
1007 jsr166 1.40 * More formally, removes the first element {@code e} such that
1008     * {@code o.equals(e)} (if such an element exists).
1009     * Returns {@code true} if this deque contained the specified element
1010 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
1011 jsr166 1.9 *
1012 jsr166 1.46 * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1013 dl 1.1 *
1014 jsr166 1.9 * @param o element to be removed from this deque, if present
1015 jsr166 1.40 * @return {@code true} if this deque contained the specified element
1016 dl 1.1 */
1017 jsr166 1.9 public boolean remove(Object o) {
1018     return removeFirstOccurrence(o);
1019 dl 1.1 }
1020    
1021     /**
1022     * Removes all of the elements from this deque.
1023 jsr166 1.7 * The deque will be empty after this call returns.
1024 dl 1.1 */
1025     public void clear() {
1026 jsr166 1.89 clearSlice(elements, head, size);
1027 jsr166 1.75 size = head = 0;
1028     // checkInvariants();
1029 dl 1.1 }
1030    
1031     /**
1032 jsr166 1.90 * Nulls out count elements, starting at array index from.
1033 jsr166 1.89 */
1034 jsr166 1.96 private static void clearSlice(Object[] es, int from, int count) {
1035     final int capacity = es.length, end = from + count;
1036 jsr166 1.89 final int leg = (capacity - end >= 0) ? end : capacity;
1037 jsr166 1.96 Arrays.fill(es, from, leg, null);
1038 jsr166 1.89 if (leg != end)
1039 jsr166 1.96 Arrays.fill(es, 0, end - capacity, null);
1040 jsr166 1.89 }
1041    
1042     /**
1043 dl 1.5 * Returns an array containing all of the elements in this deque
1044 jsr166 1.10 * in proper sequence (from first to last element).
1045 dl 1.1 *
1046 jsr166 1.10 * <p>The returned array will be "safe" in that no references to it are
1047     * maintained by this deque. (In other words, this method must allocate
1048     * a new array). The caller is thus free to modify the returned array.
1049 jsr166 1.13 *
1050 jsr166 1.11 * <p>This method acts as bridge between array-based and collection-based
1051     * APIs.
1052     *
1053 dl 1.5 * @return an array containing all of the elements in this deque
1054 dl 1.1 */
1055     public Object[] toArray() {
1056 jsr166 1.86 return toArray(Object[].class);
1057     }
1058    
1059     private <T> T[] toArray(Class<T[]> klazz) {
1060     final Object[] elements = this.elements;
1061     final int capacity = elements.length;
1062 jsr166 1.89 final int head = this.head, end = head + size;
1063 jsr166 1.86 final T[] a;
1064 jsr166 1.89 if (end >= 0) {
1065     a = Arrays.copyOfRange(elements, head, end, klazz);
1066 jsr166 1.86 } else {
1067     // integer overflow!
1068     a = Arrays.copyOfRange(elements, 0, size, klazz);
1069     System.arraycopy(elements, head, a, 0, capacity - head);
1070     }
1071 jsr166 1.89 if (end - capacity > 0)
1072     System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1073 jsr166 1.50 return a;
1074 dl 1.1 }
1075    
1076     /**
1077 jsr166 1.10 * Returns an array containing all of the elements in this deque in
1078     * proper sequence (from first to last element); the runtime type of the
1079     * returned array is that of the specified array. If the deque fits in
1080     * the specified array, it is returned therein. Otherwise, a new array
1081     * is allocated with the runtime type of the specified array and the
1082     * size of this deque.
1083     *
1084     * <p>If this deque fits in the specified array with room to spare
1085     * (i.e., the array has more elements than this deque), the element in
1086     * the array immediately following the end of the deque is set to
1087 jsr166 1.40 * {@code null}.
1088 jsr166 1.10 *
1089     * <p>Like the {@link #toArray()} method, this method acts as bridge between
1090     * array-based and collection-based APIs. Further, this method allows
1091     * precise control over the runtime type of the output array, and may,
1092     * under certain circumstances, be used to save allocation costs.
1093     *
1094 jsr166 1.40 * <p>Suppose {@code x} is a deque known to contain only strings.
1095 jsr166 1.10 * The following code can be used to dump the deque into a newly
1096 jsr166 1.40 * allocated array of {@code String}:
1097 jsr166 1.10 *
1098 jsr166 1.63 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1099 jsr166 1.10 *
1100 jsr166 1.40 * Note that {@code toArray(new Object[0])} is identical in function to
1101     * {@code toArray()}.
1102 dl 1.1 *
1103     * @param a the array into which the elements of the deque are to
1104 jsr166 1.9 * be stored, if it is big enough; otherwise, a new array of the
1105     * same runtime type is allocated for this purpose
1106 jsr166 1.10 * @return an array containing all of the elements in this deque
1107     * @throws ArrayStoreException if the runtime type of the specified array
1108     * is not a supertype of the runtime type of every element in
1109     * this deque
1110     * @throws NullPointerException if the specified array is null
1111 dl 1.1 */
1112 jsr166 1.34 @SuppressWarnings("unchecked")
1113 dl 1.1 public <T> T[] toArray(T[] a) {
1114 jsr166 1.86 final int size = this.size;
1115     if (size > a.length)
1116     return toArray((Class<T[]>) a.getClass());
1117 jsr166 1.75 final Object[] elements = this.elements;
1118 jsr166 1.86 final int capacity = elements.length;
1119 jsr166 1.89 final int head = this.head, end = head + size;
1120     final int front = (capacity - end >= 0) ? size : capacity - head;
1121     System.arraycopy(elements, head, a, 0, front);
1122     if (front != size)
1123     System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1124 jsr166 1.86 if (size < a.length)
1125     a[size] = null;
1126 dl 1.1 return a;
1127     }
1128    
1129     // *** Object methods ***
1130    
1131     /**
1132     * Returns a copy of this deque.
1133     *
1134     * @return a copy of this deque
1135     */
1136     public ArrayDeque<E> clone() {
1137 dl 1.5 try {
1138 jsr166 1.34 @SuppressWarnings("unchecked")
1139 dl 1.1 ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
1140 jsr166 1.28 result.elements = Arrays.copyOf(elements, elements.length);
1141 dl 1.1 return result;
1142 dl 1.5 } catch (CloneNotSupportedException e) {
1143 dl 1.1 throw new AssertionError();
1144     }
1145     }
1146    
1147     private static final long serialVersionUID = 2340985798034038923L;
1148    
1149     /**
1150 jsr166 1.38 * Saves this deque to a stream (that is, serializes it).
1151 dl 1.1 *
1152 jsr166 1.56 * @param s the stream
1153 jsr166 1.57 * @throws java.io.IOException if an I/O error occurs
1154 jsr166 1.40 * @serialData The current size ({@code int}) of the deque,
1155 dl 1.1 * followed by all of its elements (each an object reference) in
1156     * first-to-last order.
1157     */
1158 jsr166 1.32 private void writeObject(java.io.ObjectOutputStream s)
1159     throws java.io.IOException {
1160 dl 1.1 s.defaultWriteObject();
1161    
1162     // Write out size
1163 jsr166 1.75 s.writeInt(size);
1164 dl 1.1
1165     // Write out elements in order.
1166 jsr166 1.75 final Object[] elements = this.elements;
1167     final int capacity = elements.length;
1168 jsr166 1.92 int i, end, to, todo;
1169     todo = (end = (i = head) + size)
1170 jsr166 1.89 - (to = (capacity - end >= 0) ? end : capacity);
1171 jsr166 1.94 for (;; to = todo, i = 0, todo = 0) {
1172 jsr166 1.92 for (; i < to; i++)
1173 jsr166 1.89 s.writeObject(elements[i]);
1174 jsr166 1.90 if (todo == 0) break;
1175 jsr166 1.89 }
1176 dl 1.1 }
1177    
1178     /**
1179 jsr166 1.38 * Reconstitutes this deque from a stream (that is, deserializes it).
1180 jsr166 1.56 * @param s the stream
1181 jsr166 1.57 * @throws ClassNotFoundException if the class of a serialized object
1182     * could not be found
1183     * @throws java.io.IOException if an I/O error occurs
1184 dl 1.1 */
1185 jsr166 1.32 private void readObject(java.io.ObjectInputStream s)
1186     throws java.io.IOException, ClassNotFoundException {
1187 dl 1.1 s.defaultReadObject();
1188    
1189     // Read in size and allocate array
1190 jsr166 1.75 elements = new Object[size = s.readInt()];
1191 dl 1.1
1192     // Read in all elements in the proper order.
1193     for (int i = 0; i < size; i++)
1194 jsr166 1.34 elements[i] = s.readObject();
1195 dl 1.1 }
1196 dl 1.41
1197 jsr166 1.75 /** debugging */
1198 jsr166 1.89 void checkInvariants() {
1199 jsr166 1.75 try {
1200     int capacity = elements.length;
1201 jsr166 1.89 // assert size >= 0 && size <= capacity;
1202     // assert head >= 0;
1203     // assert capacity == 0 || head < capacity;
1204     // assert size == 0 || elements[head] != null;
1205     // assert size == 0 || elements[tail()] != null;
1206     // assert size == capacity || elements[dec(head, capacity)] == null;
1207     // assert size == capacity || elements[inc(tail(), capacity)] == null;
1208 jsr166 1.75 } catch (Throwable t) {
1209     System.err.printf("head=%d size=%d capacity=%d%n",
1210     head, size, elements.length);
1211     System.err.printf("elements=%s%n",
1212     Arrays.toString(elements));
1213     throw t;
1214 dl 1.41 }
1215     }
1216    
1217 dl 1.1 }