ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.79
Committed: Tue Oct 18 20:32:55 2016 UTC (7 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.78: +24 -28 lines
Log Message:
no new public methods in jdk 9

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