ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.55
Committed: Thu May 2 06:02:17 2013 UTC (11 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.54: +0 -1 lines
Log Message:
port to latest lambda

File Contents

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