ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.115
Committed: Fri Nov 18 03:48:28 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.114: +2 -3 lines
Log Message:
revert overkill optimization without benchmark support

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 * VMs excel at optimizing simple array loops where indices are
65 * incrementing or decrementing over a valid slice, e.g.
66 *
67 * for (int i = start; i < end; i++) ... elements[i]
68 *
69 * Because in a circular array, elements are in general stored in
70 * two disjoint such slices, we help the VM by writing unusual
71 * nested loops for all traversals over the elements. Having only
72 * one hot inner loop body instead of two or three eases human
73 * maintenance and encourages VM loop inlining into the caller.
74 */
75
76 /**
77 * The array in which the elements of the deque are stored.
78 * All array cells not holding deque elements are always null.
79 * The array always has at least one null slot (at tail).
80 */
81 transient Object[] elements;
82
83 /**
84 * The index of the element at the head of the deque (which is the
85 * element that would be removed by remove() or pop()); or an
86 * arbitrary number 0 <= head < elements.length equal to tail if
87 * the deque is empty.
88 */
89 transient int head;
90
91 /**
92 * The index at which the next element would be added to the tail
93 * of the deque (via addLast(E), add(E), or push(E));
94 * elements[tail] is always null.
95 */
96 transient int tail;
97
98 /**
99 * The maximum size of array to allocate.
100 * Some VMs reserve some header words in an array.
101 * Attempts to allocate larger arrays may result in
102 * OutOfMemoryError: Requested array size exceeds VM limit
103 */
104 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
105
106 /**
107 * Increases the capacity of this deque by at least the given amount.
108 *
109 * @param needed the required minimum extra capacity; must be positive
110 */
111 private void grow(int needed) {
112 // overflow-conscious code
113 final int oldCapacity = elements.length;
114 int newCapacity;
115 // Double capacity if small; else grow by 50%
116 int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
117 if (jump < needed
118 || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
119 newCapacity = newCapacity(needed, jump);
120 elements = Arrays.copyOf(elements, newCapacity);
121 // Exceptionally, here tail == head needs to be disambiguated
122 if (tail < head || (tail == head && elements[head] != null)) {
123 // wrap around; slide first leg forward to end of array
124 int newSpace = newCapacity - oldCapacity;
125 System.arraycopy(elements, head,
126 elements, head + newSpace,
127 oldCapacity - head);
128 Arrays.fill(elements, head, head + newSpace, null);
129 head += newSpace;
130 }
131 // checkInvariants();
132 }
133
134 /** Capacity calculation for edge conditions, especially overflow. */
135 private int newCapacity(int needed, int jump) {
136 final int oldCapacity = elements.length, minCapacity;
137 if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
138 if (minCapacity < 0)
139 throw new IllegalStateException("Sorry, deque too big");
140 return Integer.MAX_VALUE;
141 }
142 if (needed > jump)
143 return minCapacity;
144 return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
145 ? oldCapacity + jump
146 : MAX_ARRAY_SIZE;
147 }
148
149 /**
150 * Increases the internal storage of this collection, if necessary,
151 * to ensure that it can hold at least the given number of elements.
152 *
153 * @param minCapacity the desired minimum capacity
154 * @since TBD
155 */
156 /* public */ void ensureCapacity(int minCapacity) {
157 int needed;
158 if ((needed = (minCapacity + 1 - elements.length)) > 0)
159 grow(needed);
160 // checkInvariants();
161 }
162
163 /**
164 * Minimizes the internal storage of this collection.
165 *
166 * @since TBD
167 */
168 /* public */ void trimToSize() {
169 int size;
170 if ((size = size()) + 1 < elements.length) {
171 elements = toArray(new Object[size + 1]);
172 head = 0;
173 tail = size;
174 }
175 // checkInvariants();
176 }
177
178 /**
179 * Constructs an empty array deque with an initial capacity
180 * sufficient to hold 16 elements.
181 */
182 public ArrayDeque() {
183 elements = new Object[16];
184 }
185
186 /**
187 * Constructs an empty array deque with an initial capacity
188 * sufficient to hold the specified number of elements.
189 *
190 * @param numElements lower bound on initial capacity of the deque
191 */
192 public ArrayDeque(int numElements) {
193 elements =
194 new Object[(numElements < 1) ? 1 :
195 (numElements == Integer.MAX_VALUE) ? Integer.MAX_VALUE :
196 numElements + 1];
197 }
198
199 /**
200 * Constructs a deque containing the elements of the specified
201 * collection, in the order they are returned by the collection's
202 * iterator. (The first element returned by the collection's
203 * iterator becomes the first element, or <i>front</i> of the
204 * deque.)
205 *
206 * @param c the collection whose elements are to be placed into the deque
207 * @throws NullPointerException if the specified collection is null
208 */
209 public ArrayDeque(Collection<? extends E> c) {
210 this(c.size());
211 addAll(c);
212 }
213
214 /**
215 * Increments i, mod modulus.
216 * Precondition and postcondition: 0 <= i < modulus.
217 */
218 static final int inc(int i, int modulus) {
219 if (++i >= modulus) i = 0;
220 return i;
221 }
222
223 /**
224 * Decrements i, mod modulus.
225 * Precondition and postcondition: 0 <= i < modulus.
226 */
227 static final int dec(int i, int modulus) {
228 if (--i < 0) i = modulus - 1;
229 return i;
230 }
231
232 /**
233 * Circularly adds the given distance to index i, mod modulus.
234 * Precondition: 0 <= i < modulus, 0 <= distance <= modulus.
235 * @return index 0 <= i < modulus
236 */
237 static final int add(int i, int distance, int modulus) {
238 if ((i += distance) - modulus >= 0) distance -= modulus;
239 return i;
240 }
241
242 /**
243 * Subtracts j from i, mod modulus.
244 * Index i must be logically ahead of index j.
245 * Precondition: 0 <= i < modulus, 0 <= j < modulus.
246 * @return the "circular distance" from j to i; corner case i == j
247 * is diambiguated to "empty", returning 0.
248 */
249 static final int sub(int i, int j, int modulus) {
250 if ((i -= j) < 0) i += modulus;
251 return i;
252 }
253
254 /**
255 * Returns element at array index i.
256 * This is a slight abuse of generics, accepted by javac.
257 */
258 @SuppressWarnings("unchecked")
259 static final <E> E elementAt(Object[] es, int i) {
260 return (E) es[i];
261 }
262
263 /**
264 * A version of elementAt that checks for null elements.
265 * This check doesn't catch all possible comodifications,
266 * but does catch ones that corrupt traversal.
267 */
268 static final <E> E nonNullElementAt(Object[] es, int i) {
269 @SuppressWarnings("unchecked") E e = (E) es[i];
270 if (e == null)
271 throw new ConcurrentModificationException();
272 return e;
273 }
274
275 // The main insertion and extraction methods are addFirst,
276 // addLast, pollFirst, pollLast. The other methods are defined in
277 // terms of these.
278
279 /**
280 * Inserts the specified element at the front of this deque.
281 *
282 * @param e the element to add
283 * @throws NullPointerException if the specified element is null
284 */
285 public void addFirst(E e) {
286 if (e == null)
287 throw new NullPointerException();
288 final Object[] es = elements;
289 es[head = dec(head, es.length)] = e;
290 if (head == tail)
291 grow(1);
292 // checkInvariants();
293 }
294
295 /**
296 * Inserts the specified element at the end of this deque.
297 *
298 * <p>This method is equivalent to {@link #add}.
299 *
300 * @param e the element to add
301 * @throws NullPointerException if the specified element is null
302 */
303 public void addLast(E e) {
304 if (e == null)
305 throw new NullPointerException();
306 final Object[] es = elements;
307 es[tail] = e;
308 if (head == (tail = inc(tail, es.length)))
309 grow(1);
310 // checkInvariants();
311 }
312
313 /**
314 * Adds all of the elements in the specified collection at the end
315 * of this deque, as if by calling {@link #addLast} on each one,
316 * in the order that they are returned by the collection's
317 * iterator.
318 *
319 * @param c the elements to be inserted into this deque
320 * @return {@code true} if this deque changed as a result of the call
321 * @throws NullPointerException if the specified collection or any
322 * of its elements are null
323 */
324 public boolean addAll(Collection<? extends E> c) {
325 final int s = size(), needed;
326 if ((needed = s + c.size() - elements.length + 1) > 0)
327 grow(needed);
328 c.forEach(e -> addLast(e));
329 // checkInvariants();
330 return size() > s;
331 }
332
333 /**
334 * Inserts the specified element at the front of this deque.
335 *
336 * @param e the element to add
337 * @return {@code true} (as specified by {@link Deque#offerFirst})
338 * @throws NullPointerException if the specified element is null
339 */
340 public boolean offerFirst(E e) {
341 addFirst(e);
342 return true;
343 }
344
345 /**
346 * Inserts the specified element at the end of this deque.
347 *
348 * @param e the element to add
349 * @return {@code true} (as specified by {@link Deque#offerLast})
350 * @throws NullPointerException if the specified element is null
351 */
352 public boolean offerLast(E e) {
353 addLast(e);
354 return true;
355 }
356
357 /**
358 * @throws NoSuchElementException {@inheritDoc}
359 */
360 public E removeFirst() {
361 E e = pollFirst();
362 if (e == null)
363 throw new NoSuchElementException();
364 // checkInvariants();
365 return e;
366 }
367
368 /**
369 * @throws NoSuchElementException {@inheritDoc}
370 */
371 public E removeLast() {
372 E e = pollLast();
373 if (e == null)
374 throw new NoSuchElementException();
375 // checkInvariants();
376 return e;
377 }
378
379 public E pollFirst() {
380 final Object[] es;
381 final int h;
382 E e = elementAt(es = elements, h = head);
383 if (e != null) {
384 es[h] = null;
385 head = inc(h, es.length);
386 }
387 // checkInvariants();
388 return e;
389 }
390
391 public E pollLast() {
392 final Object[] es;
393 final int t;
394 E e = elementAt(es = elements, t = dec(tail, es.length));
395 if (e != null)
396 es[tail = t] = null;
397 // checkInvariants();
398 return e;
399 }
400
401 /**
402 * @throws NoSuchElementException {@inheritDoc}
403 */
404 public E getFirst() {
405 E e = elementAt(elements, head);
406 if (e == null)
407 throw new NoSuchElementException();
408 // checkInvariants();
409 return e;
410 }
411
412 /**
413 * @throws NoSuchElementException {@inheritDoc}
414 */
415 public E getLast() {
416 final Object[] es = elements;
417 E e = elementAt(es, dec(tail, es.length));
418 if (e == null)
419 throw new NoSuchElementException();
420 // checkInvariants();
421 return e;
422 }
423
424 public E peekFirst() {
425 // checkInvariants();
426 return elementAt(elements, head);
427 }
428
429 public E peekLast() {
430 // checkInvariants();
431 final Object[] es;
432 return elementAt(es = elements, dec(tail, es.length));
433 }
434
435 /**
436 * Removes the first occurrence of the specified element in this
437 * deque (when traversing the deque from head to tail).
438 * If the deque does not contain the element, it is unchanged.
439 * More formally, removes the first element {@code e} such that
440 * {@code o.equals(e)} (if such an element exists).
441 * Returns {@code true} if this deque contained the specified element
442 * (or equivalently, if this deque changed as a result of the call).
443 *
444 * @param o element to be removed from this deque, if present
445 * @return {@code true} if the deque contained the specified element
446 */
447 public boolean removeFirstOccurrence(Object o) {
448 if (o != null) {
449 final Object[] es = elements;
450 for (int i = head, end = tail, to = (i <= end) ? end : es.length;
451 ; i = 0, to = end) {
452 for (; i < to; i++)
453 if (o.equals(es[i])) {
454 delete(i);
455 return true;
456 }
457 if (to == end) break;
458 }
459 }
460 return false;
461 }
462
463 /**
464 * Removes the last occurrence of the specified element in this
465 * deque (when traversing the deque from head to tail).
466 * If the deque does not contain the element, it is unchanged.
467 * More formally, removes the last element {@code e} such that
468 * {@code o.equals(e)} (if such an element exists).
469 * Returns {@code true} if this deque contained the specified element
470 * (or equivalently, if this deque changed as a result of the call).
471 *
472 * @param o element to be removed from this deque, if present
473 * @return {@code true} if the deque contained the specified element
474 */
475 public boolean removeLastOccurrence(Object o) {
476 if (o != null) {
477 final Object[] es = elements;
478 for (int i = tail, end = head, to = (i >= end) ? end : 0;
479 ; i = es.length, to = end) {
480 for (i--; i > to - 1; i--)
481 if (o.equals(es[i])) {
482 delete(i);
483 return true;
484 }
485 if (to == end) break;
486 }
487 }
488 return false;
489 }
490
491 // *** Queue methods ***
492
493 /**
494 * Inserts the specified element at the end of this deque.
495 *
496 * <p>This method is equivalent to {@link #addLast}.
497 *
498 * @param e the element to add
499 * @return {@code true} (as specified by {@link Collection#add})
500 * @throws NullPointerException if the specified element is null
501 */
502 public boolean add(E e) {
503 addLast(e);
504 return true;
505 }
506
507 /**
508 * Inserts the specified element at the end of this deque.
509 *
510 * <p>This method is equivalent to {@link #offerLast}.
511 *
512 * @param e the element to add
513 * @return {@code true} (as specified by {@link Queue#offer})
514 * @throws NullPointerException if the specified element is null
515 */
516 public boolean offer(E e) {
517 return offerLast(e);
518 }
519
520 /**
521 * Retrieves and removes the head of the queue represented by this deque.
522 *
523 * This method differs from {@link #poll poll} only in that it throws an
524 * exception if this deque is empty.
525 *
526 * <p>This method is equivalent to {@link #removeFirst}.
527 *
528 * @return the head of the queue represented by this deque
529 * @throws NoSuchElementException {@inheritDoc}
530 */
531 public E remove() {
532 return removeFirst();
533 }
534
535 /**
536 * 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 * {@code null} if this deque is empty.
539 *
540 * <p>This method is equivalent to {@link #pollFirst}.
541 *
542 * @return the head of the queue represented by this deque, or
543 * {@code null} if this deque is empty
544 */
545 public E poll() {
546 return pollFirst();
547 }
548
549 /**
550 * Retrieves, but does not remove, the head of the queue represented by
551 * this deque. This method differs from {@link #peek peek} only in
552 * that it throws an exception if this deque is empty.
553 *
554 * <p>This method is equivalent to {@link #getFirst}.
555 *
556 * @return the head of the queue represented by this deque
557 * @throws NoSuchElementException {@inheritDoc}
558 */
559 public E element() {
560 return getFirst();
561 }
562
563 /**
564 * Retrieves, but does not remove, the head of the queue represented by
565 * this deque, or returns {@code null} if this deque is empty.
566 *
567 * <p>This method is equivalent to {@link #peekFirst}.
568 *
569 * @return the head of the queue represented by this deque, or
570 * {@code null} if this deque is empty
571 */
572 public E peek() {
573 return peekFirst();
574 }
575
576 // *** Stack methods ***
577
578 /**
579 * Pushes an element onto the stack represented by this deque. In other
580 * words, inserts the element at the front of this deque.
581 *
582 * <p>This method is equivalent to {@link #addFirst}.
583 *
584 * @param e the element to push
585 * @throws NullPointerException if the specified element is null
586 */
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 * words, removes and returns the first element of this deque.
594 *
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 * of the stack represented by this deque)
599 * @throws NoSuchElementException {@inheritDoc}
600 */
601 public E pop() {
602 return removeFirst();
603 }
604
605 /**
606 * 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 *
610 * <p>This method is called delete rather than remove to emphasize
611 * that its semantics differ from those of {@link List#remove(int)}.
612 *
613 * @return true if elements near tail moved backwards
614 */
615 boolean delete(int i) {
616 // checkInvariants();
617 final Object[] es = elements;
618 final int capacity = es.length;
619 final int h = head;
620 // number of elements before to-be-deleted elt
621 final int front = sub(i, h, capacity);
622 final int back = size() - front - 1; // number of elements after
623 if (front < back) {
624 // move front elements forwards
625 if (h <= i) {
626 System.arraycopy(es, h, es, h + 1, front);
627 } else { // Wrap around
628 System.arraycopy(es, 0, es, 1, i);
629 es[0] = es[capacity - 1];
630 System.arraycopy(es, h, es, h + 1, front - (i + 1));
631 }
632 es[h] = null;
633 head = inc(h, capacity);
634 // checkInvariants();
635 return false;
636 } else {
637 // move back elements backwards
638 tail = dec(tail, capacity);
639 if (i <= tail) {
640 System.arraycopy(es, i + 1, es, i, back);
641 } else { // Wrap around
642 int firstLeg = capacity - (i + 1);
643 System.arraycopy(es, i + 1, es, i, firstLeg);
644 es[capacity - 1] = es[0];
645 System.arraycopy(es, 1, es, 0, back - firstLeg - 1);
646 }
647 es[tail] = null;
648 // checkInvariants();
649 return true;
650 }
651 }
652
653 // *** Collection Methods ***
654
655 /**
656 * Returns the number of elements in this deque.
657 *
658 * @return the number of elements in this deque
659 */
660 public int size() {
661 return sub(tail, head, elements.length);
662 }
663
664 /**
665 * Returns {@code true} if this deque contains no elements.
666 *
667 * @return {@code true} if this deque contains no elements
668 */
669 public boolean isEmpty() {
670 return head == tail;
671 }
672
673 /**
674 * Returns an iterator over the elements in this deque. The elements
675 * will be ordered from first (head) to last (tail). This is the same
676 * order that elements would be dequeued (via successive calls to
677 * {@link #remove} or popped (via successive calls to {@link #pop}).
678 *
679 * @return an iterator over the elements in this deque
680 */
681 public Iterator<E> iterator() {
682 return new DeqIterator();
683 }
684
685 public Iterator<E> descendingIterator() {
686 return new DescendingIterator();
687 }
688
689 private class DeqIterator implements Iterator<E> {
690 /** Index of element to be returned by subsequent call to next. */
691 int cursor;
692
693 /** Number of elements yet to be returned. */
694 int remaining = size();
695
696 /**
697 * Index of element returned by most recent call to next.
698 * Reset to -1 if element is deleted by a call to remove.
699 */
700 int lastRet = -1;
701
702 DeqIterator() { cursor = head; }
703
704 public final boolean hasNext() {
705 return remaining > 0;
706 }
707
708 public E next() {
709 if (remaining <= 0)
710 throw new NoSuchElementException();
711 final Object[] es = elements;
712 E e = nonNullElementAt(es, cursor);
713 lastRet = cursor;
714 cursor = inc(cursor, es.length);
715 remaining--;
716 return e;
717 }
718
719 void postDelete(boolean leftShifted) {
720 if (leftShifted)
721 cursor = dec(cursor, elements.length);
722 }
723
724 public final void remove() {
725 if (lastRet < 0)
726 throw new IllegalStateException();
727 postDelete(delete(lastRet));
728 lastRet = -1;
729 }
730
731 public void forEachRemaining(Consumer<? super E> action) {
732 Objects.requireNonNull(action);
733 int r;
734 if ((r = remaining) <= 0)
735 return;
736 remaining = 0;
737 final Object[] es = elements;
738 if (es[cursor] == null || sub(tail, cursor, es.length) != r)
739 throw new ConcurrentModificationException();
740 for (int i = cursor, end = tail, to = (i <= end) ? end : es.length;
741 ; i = 0, to = end) {
742 for (; i < to; i++)
743 action.accept(elementAt(es, i));
744 if (to == end) {
745 if (end != tail)
746 throw new ConcurrentModificationException();
747 lastRet = dec(end, es.length);
748 break;
749 }
750 }
751 }
752 }
753
754 private class DescendingIterator extends DeqIterator {
755 DescendingIterator() { cursor = dec(tail, elements.length); }
756
757 public final E next() {
758 if (remaining <= 0)
759 throw new NoSuchElementException();
760 final Object[] es = elements;
761 E e = nonNullElementAt(es, cursor);
762 lastRet = cursor;
763 cursor = dec(cursor, es.length);
764 remaining--;
765 return e;
766 }
767
768 void postDelete(boolean leftShifted) {
769 if (!leftShifted)
770 cursor = inc(cursor, elements.length);
771 }
772
773 public final void forEachRemaining(Consumer<? super E> action) {
774 Objects.requireNonNull(action);
775 int r;
776 if ((r = remaining) <= 0)
777 return;
778 remaining = 0;
779 final Object[] es = elements;
780 if (es[cursor] == null || sub(cursor, head, es.length) + 1 != r)
781 throw new ConcurrentModificationException();
782 for (int i = cursor, end = head, to = (i >= end) ? end : 0;
783 ; i = es.length - 1, to = end) {
784 // hotspot generates faster code than for: i >= to !
785 for (; i > to - 1; i--)
786 action.accept(elementAt(es, i));
787 if (to == end) {
788 if (end != head)
789 throw new ConcurrentModificationException();
790 lastRet = end;
791 break;
792 }
793 }
794 }
795 }
796
797 /**
798 * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
799 * and <em>fail-fast</em> {@link Spliterator} over the elements in this
800 * deque.
801 *
802 * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
803 * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
804 * {@link Spliterator#NONNULL}. Overriding implementations should document
805 * the reporting of additional characteristic values.
806 *
807 * @return a {@code Spliterator} over the elements in this deque
808 * @since 1.8
809 */
810 public Spliterator<E> spliterator() {
811 return new DeqSpliterator();
812 }
813
814 final class DeqSpliterator implements Spliterator<E> {
815 private int fence; // -1 until first use
816 private int cursor; // current index, modified on traverse/split
817
818 /** Constructs late-binding spliterator over all elements. */
819 DeqSpliterator() {
820 this.fence = -1;
821 }
822
823 /** Constructs spliterator over the given range. */
824 DeqSpliterator(int origin, int fence) {
825 this.cursor = origin;
826 this.fence = fence;
827 }
828
829 /** Ensures late-binding initialization; then returns fence. */
830 private int getFence() { // force initialization
831 int t;
832 if ((t = fence) < 0) {
833 t = fence = tail;
834 cursor = head;
835 }
836 return t;
837 }
838
839 public DeqSpliterator trySplit() {
840 final Object[] es = elements;
841 final int i, n;
842 return ((n = sub(getFence(), i = cursor, es.length) >> 1) <= 0)
843 ? null
844 : new DeqSpliterator(i, cursor = add(i, n, es.length));
845 }
846
847 public void forEachRemaining(Consumer<? super E> action) {
848 if (action == null)
849 throw new NullPointerException();
850 final int end = getFence(), cursor = this.cursor;
851 final Object[] es = elements;
852 if (cursor != end) {
853 this.cursor = end;
854 // null check at both ends of range is sufficient
855 if (es[cursor] == null || es[dec(end, es.length)] == null)
856 throw new ConcurrentModificationException();
857 for (int i = cursor, to = (i <= end) ? end : es.length;
858 ; i = 0, to = end) {
859 for (; i < to; i++)
860 action.accept(elementAt(es, i));
861 if (to == end) break;
862 }
863 }
864 }
865
866 public boolean tryAdvance(Consumer<? super E> action) {
867 if (action == null)
868 throw new NullPointerException();
869 final int t, i;
870 if ((t = getFence()) == (i = cursor))
871 return false;
872 final Object[] es = elements;
873 cursor = inc(i, es.length);
874 action.accept(nonNullElementAt(es, i));
875 return true;
876 }
877
878 public long estimateSize() {
879 return sub(getFence(), cursor, elements.length);
880 }
881
882 public int characteristics() {
883 return Spliterator.NONNULL
884 | Spliterator.ORDERED
885 | Spliterator.SIZED
886 | Spliterator.SUBSIZED;
887 }
888 }
889
890 public void forEach(Consumer<? super E> action) {
891 Objects.requireNonNull(action);
892 final Object[] es = elements;
893 for (int i = head, end = tail, to = (i <= end) ? end : es.length;
894 ; i = 0, to = end) {
895 for (; i < to; i++)
896 action.accept(elementAt(es, i));
897 if (to == end) {
898 if (end != tail) throw new ConcurrentModificationException();
899 break;
900 }
901 }
902 // checkInvariants();
903 }
904
905 /**
906 * Replaces each element of this deque with the result of applying the
907 * operator to that element, as specified by {@link List#replaceAll}.
908 *
909 * @param operator the operator to apply to each element
910 * @since TBD
911 */
912 /* public */ void replaceAll(UnaryOperator<E> operator) {
913 Objects.requireNonNull(operator);
914 final Object[] es = elements;
915 for (int i = head, end = tail, to = (i <= end) ? end : es.length;
916 ; i = 0, to = end) {
917 for (; i < to; i++)
918 es[i] = operator.apply(elementAt(es, i));
919 if (to == end) {
920 if (end != tail) throw new ConcurrentModificationException();
921 break;
922 }
923 }
924 // checkInvariants();
925 }
926
927 /**
928 * @throws NullPointerException {@inheritDoc}
929 */
930 public boolean removeIf(Predicate<? super E> filter) {
931 Objects.requireNonNull(filter);
932 return bulkRemove(filter);
933 }
934
935 /**
936 * @throws NullPointerException {@inheritDoc}
937 */
938 public boolean removeAll(Collection<?> c) {
939 Objects.requireNonNull(c);
940 return bulkRemove(e -> c.contains(e));
941 }
942
943 /**
944 * @throws NullPointerException {@inheritDoc}
945 */
946 public boolean retainAll(Collection<?> c) {
947 Objects.requireNonNull(c);
948 return bulkRemove(e -> !c.contains(e));
949 }
950
951 /** Implementation of bulk remove methods. */
952 private boolean bulkRemove(Predicate<? super E> filter) {
953 // checkInvariants();
954 final Object[] es = elements;
955 // Optimize for initial run of survivors
956 for (int i = head, end = tail, to = (i <= end) ? end : es.length;
957 ; i = 0, to = end) {
958 for (; i < to; i++)
959 if (filter.test(elementAt(es, i)))
960 return bulkRemoveModified(filter, i);
961 if (to == end) {
962 if (end != tail) throw new ConcurrentModificationException();
963 break;
964 }
965 }
966 return false;
967 }
968
969 // A tiny bit set implementation
970
971 private static long[] nBits(int n) {
972 return new long[((n - 1) >> 6) + 1];
973 }
974 private static void setBit(long[] bits, int i) {
975 bits[i >> 6] |= 1L << i;
976 }
977 private static boolean isClear(long[] bits, int i) {
978 return (bits[i >> 6] & (1L << i)) == 0;
979 }
980
981 /**
982 * Helper for bulkRemove, in case of at least one deletion.
983 * Tolerate predicates that reentrantly access the collection for
984 * read (but writers still get CME), so traverse once to find
985 * elements to delete, a second pass to physically expunge.
986 *
987 * @param beg valid index of first element to be deleted
988 */
989 private boolean bulkRemoveModified(
990 Predicate<? super E> filter, final int beg) {
991 final Object[] es = elements;
992 final int capacity = es.length;
993 final int end = tail;
994 final long[] deathRow = nBits(sub(end, beg, capacity));
995 deathRow[0] = 1L; // set bit 0
996 for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
997 ; i = 0, to = end, k -= capacity) {
998 for (; i < to; i++)
999 if (filter.test(elementAt(es, i)))
1000 setBit(deathRow, i - k);
1001 if (to == end) break;
1002 }
1003 // a two-finger traversal, with hare i reading, tortoise w writing
1004 int w = beg;
1005 for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
1006 ; w = 0) { // w rejoins i on second leg
1007 // In this loop, i and w are on the same leg, with i > w
1008 for (; i < to; i++)
1009 if (isClear(deathRow, i - k))
1010 es[w++] = es[i];
1011 if (to == end) break;
1012 // In this loop, w is on the first leg, i on the second
1013 for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++)
1014 if (isClear(deathRow, i - k))
1015 es[w++] = es[i];
1016 if (i >= to) {
1017 if (w == capacity) w = 0; // "corner" case
1018 break;
1019 }
1020 }
1021 if (end != tail) throw new ConcurrentModificationException();
1022 circularClear(es, tail = w, end);
1023 // checkInvariants();
1024 return true;
1025 }
1026
1027 /**
1028 * Returns {@code true} if this deque contains the specified element.
1029 * More formally, returns {@code true} if and only if this deque contains
1030 * at least one element {@code e} such that {@code o.equals(e)}.
1031 *
1032 * @param o object to be checked for containment in this deque
1033 * @return {@code true} if this deque contains the specified element
1034 */
1035 public boolean contains(Object o) {
1036 if (o != null) {
1037 final Object[] es = elements;
1038 for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1039 ; i = 0, to = end) {
1040 for (; i < to; i++)
1041 if (o.equals(es[i]))
1042 return true;
1043 if (to == end) break;
1044 }
1045 }
1046 return false;
1047 }
1048
1049 /**
1050 * Removes a single instance of the specified element from this deque.
1051 * If the deque does not contain the element, it is unchanged.
1052 * More formally, removes the first element {@code e} such that
1053 * {@code o.equals(e)} (if such an element exists).
1054 * Returns {@code true} if this deque contained the specified element
1055 * (or equivalently, if this deque changed as a result of the call).
1056 *
1057 * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1058 *
1059 * @param o element to be removed from this deque, if present
1060 * @return {@code true} if this deque contained the specified element
1061 */
1062 public boolean remove(Object o) {
1063 return removeFirstOccurrence(o);
1064 }
1065
1066 /**
1067 * Removes all of the elements from this deque.
1068 * The deque will be empty after this call returns.
1069 */
1070 public void clear() {
1071 circularClear(elements, head, tail);
1072 head = tail = 0;
1073 // checkInvariants();
1074 }
1075
1076 /**
1077 * Nulls out slots starting at array index i, upto index end.
1078 */
1079 private static void circularClear(Object[] es, int i, int end) {
1080 for (int to = (i <= end) ? end : es.length;
1081 ; i = 0, to = end) {
1082 Arrays.fill(es, i, to, null);
1083 if (to == end) break;
1084 }
1085 }
1086
1087 /**
1088 * Returns an array containing all of the elements in this deque
1089 * in proper sequence (from first to last element).
1090 *
1091 * <p>The returned array will be "safe" in that no references to it are
1092 * maintained by this deque. (In other words, this method must allocate
1093 * a new array). The caller is thus free to modify the returned array.
1094 *
1095 * <p>This method acts as bridge between array-based and collection-based
1096 * APIs.
1097 *
1098 * @return an array containing all of the elements in this deque
1099 */
1100 public Object[] toArray() {
1101 return toArray(Object[].class);
1102 }
1103
1104 private <T> T[] toArray(Class<T[]> klazz) {
1105 final Object[] es = elements;
1106 final T[] a;
1107 final int size = size(), head = this.head, end;
1108 final int len = Math.min(size, es.length - head);
1109 if ((end = head + size) >= 0) {
1110 a = Arrays.copyOfRange(es, head, end, klazz);
1111 } else {
1112 // integer overflow!
1113 a = Arrays.copyOfRange(es, 0, size, klazz);
1114 System.arraycopy(es, head, a, 0, len);
1115 }
1116 if (tail < head)
1117 System.arraycopy(es, 0, a, len, tail);
1118 return a;
1119 }
1120
1121 /**
1122 * Returns an array containing all of the elements in this deque in
1123 * proper sequence (from first to last element); the runtime type of the
1124 * returned array is that of the specified array. If the deque fits in
1125 * the specified array, it is returned therein. Otherwise, a new array
1126 * is allocated with the runtime type of the specified array and the
1127 * size of this deque.
1128 *
1129 * <p>If this deque fits in the specified array with room to spare
1130 * (i.e., the array has more elements than this deque), the element in
1131 * the array immediately following the end of the deque is set to
1132 * {@code null}.
1133 *
1134 * <p>Like the {@link #toArray()} method, this method acts as bridge between
1135 * array-based and collection-based APIs. Further, this method allows
1136 * precise control over the runtime type of the output array, and may,
1137 * under certain circumstances, be used to save allocation costs.
1138 *
1139 * <p>Suppose {@code x} is a deque known to contain only strings.
1140 * The following code can be used to dump the deque into a newly
1141 * allocated array of {@code String}:
1142 *
1143 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1144 *
1145 * Note that {@code toArray(new Object[0])} is identical in function to
1146 * {@code toArray()}.
1147 *
1148 * @param a the array into which the elements of the deque are to
1149 * be stored, if it is big enough; otherwise, a new array of the
1150 * same runtime type is allocated for this purpose
1151 * @return an array containing all of the elements in this deque
1152 * @throws ArrayStoreException if the runtime type of the specified array
1153 * is not a supertype of the runtime type of every element in
1154 * this deque
1155 * @throws NullPointerException if the specified array is null
1156 */
1157 @SuppressWarnings("unchecked")
1158 public <T> T[] toArray(T[] a) {
1159 final int size;
1160 if ((size = size()) > a.length)
1161 return toArray((Class<T[]>) a.getClass());
1162 final Object[] es = elements;
1163 for (int i = head, j = 0, len = Math.min(size, es.length - i);
1164 ; i = 0, len = tail) {
1165 System.arraycopy(es, i, a, j, len);
1166 if ((j += len) == size) break;
1167 }
1168 if (size < a.length)
1169 a[size] = null;
1170 return a;
1171 }
1172
1173 // *** Object methods ***
1174
1175 /**
1176 * Returns a copy of this deque.
1177 *
1178 * @return a copy of this deque
1179 */
1180 public ArrayDeque<E> clone() {
1181 try {
1182 @SuppressWarnings("unchecked")
1183 ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
1184 result.elements = Arrays.copyOf(elements, elements.length);
1185 return result;
1186 } catch (CloneNotSupportedException e) {
1187 throw new AssertionError();
1188 }
1189 }
1190
1191 private static final long serialVersionUID = 2340985798034038923L;
1192
1193 /**
1194 * Saves this deque to a stream (that is, serializes it).
1195 *
1196 * @param s the stream
1197 * @throws java.io.IOException if an I/O error occurs
1198 * @serialData The current size ({@code int}) of the deque,
1199 * followed by all of its elements (each an object reference) in
1200 * first-to-last order.
1201 */
1202 private void writeObject(java.io.ObjectOutputStream s)
1203 throws java.io.IOException {
1204 s.defaultWriteObject();
1205
1206 // Write out size
1207 s.writeInt(size());
1208
1209 // Write out elements in order.
1210 final Object[] es = elements;
1211 for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1212 ; i = 0, to = end) {
1213 for (; i < to; i++)
1214 s.writeObject(es[i]);
1215 if (to == end) break;
1216 }
1217 }
1218
1219 /**
1220 * Reconstitutes this deque from a stream (that is, deserializes it).
1221 * @param s the stream
1222 * @throws ClassNotFoundException if the class of a serialized object
1223 * could not be found
1224 * @throws java.io.IOException if an I/O error occurs
1225 */
1226 private void readObject(java.io.ObjectInputStream s)
1227 throws java.io.IOException, ClassNotFoundException {
1228 s.defaultReadObject();
1229
1230 // Read in size and allocate array
1231 int size = s.readInt();
1232 elements = new Object[size + 1];
1233 this.tail = size;
1234
1235 // Read in all elements in the proper order.
1236 for (int i = 0; i < size; i++)
1237 elements[i] = s.readObject();
1238 }
1239
1240 /** debugging */
1241 void checkInvariants() {
1242 // Use head and tail fields with empty slot at tail strategy.
1243 // head == tail disambiguates to "empty".
1244 try {
1245 int capacity = elements.length;
1246 // assert head >= 0 && head < capacity;
1247 // assert tail >= 0 && tail < capacity;
1248 // assert capacity > 0;
1249 // assert size() < capacity;
1250 // assert head == tail || elements[head] != null;
1251 // assert elements[tail] == null;
1252 // assert head == tail || elements[dec(tail, capacity)] != null;
1253 } catch (Throwable t) {
1254 System.err.printf("head=%d tail=%d capacity=%d%n",
1255 head, tail, elements.length);
1256 System.err.printf("elements=%s%n",
1257 Arrays.toString(elements));
1258 throw t;
1259 }
1260 }
1261
1262 }