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