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 java.util.function.UnaryOperator; 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}/../technotes/guides/collections/index.html"> 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]; 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 addAll(c); 211 } 212 213 /** 214 * 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 * 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 add(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 diambiguated 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 314 * iterator. 315 * 316 * @param c the elements to be inserted into this deque 317 * @return {@code true} if this deque changed as a result of the call 318 * @throws NullPointerException if the specified collection or any 319 * of its elements are null 320 * @since 9 321 */ 322 public boolean addAll(Collection<? extends E> c) { 323 final int s, needed; 324 if ((needed = (s = size()) + c.size() + 1 - elements.length) > 0) 325 grow(needed); 326 c.forEach(this::addLast); 327 return size() > s; 328 } 329 330 /** 331 * Inserts the specified element at the front of this deque. 332 * 333 * @param e the element to add 334 * @return {@code true} (as specified by {@link Deque#offerFirst}) 335 * @throws NullPointerException if the specified element is null 336 */ 337 public boolean offerFirst(E e) { 338 addFirst(e); 339 return true; 340 } 341 342 /** 343 * Inserts the specified element at the end of this deque. 344 * 345 * @param e the element to add 346 * @return {@code true} (as specified by {@link Deque#offerLast}) 347 * @throws NullPointerException if the specified element is null 348 */ 349 public boolean offerLast(E e) { 350 addLast(e); 351 return true; 352 } 353 354 /** 355 * @throws NoSuchElementException {@inheritDoc} 356 */ 357 public E removeFirst() { 358 E e = pollFirst(); 359 if (e == null) 360 throw new NoSuchElementException(); 361 return e; 362 } 363 364 /** 365 * @throws NoSuchElementException {@inheritDoc} 366 */ 367 public E removeLast() { 368 E e = pollLast(); 369 if (e == null) 370 throw new NoSuchElementException(); 371 return e; 372 } 373 374 public E pollFirst() { 375 final Object[] es; 376 final int h; 377 E e = elementAt(es = elements, h = head); 378 if (e != null) { 379 es[h] = null; 380 head = inc(h, es.length); 381 } 382 return e; 383 } 384 385 public E pollLast() { 386 final Object[] es; 387 final int t; 388 E e = elementAt(es = elements, t = dec(tail, es.length)); 389 if (e != null) 390 es[tail = t] = null; 391 return e; 392 } 393 394 /** 395 * @throws NoSuchElementException {@inheritDoc} 396 */ 397 public E getFirst() { 398 E e = elementAt(elements, head); 399 if (e == null) 400 throw new NoSuchElementException(); 401 return e; 402 } 403 404 /** 405 * @throws NoSuchElementException {@inheritDoc} 406 */ 407 public E getLast() { 408 final Object[] es = elements; 409 E e = elementAt(es, dec(tail, es.length)); 410 if (e == null) 411 throw new NoSuchElementException(); 412 return e; 413 } 414 415 public E peekFirst() { 416 return elementAt(elements, head); 417 } 418 419 public E peekLast() { 420 final Object[] es; 421 return elementAt(es = elements, dec(tail, es.length)); 422 } 423 424 /** 425 * Removes the first occurrence of the specified element in this 426 * deque (when traversing the deque from head to tail). 427 * If the deque does not contain the element, it is unchanged. 428 * More formally, removes the first element {@code e} such that 429 * {@code o.equals(e)} (if such an element exists). 430 * Returns {@code true} if this deque contained the specified element 431 * (or equivalently, if this deque changed as a result of the call). 432 * 433 * @param o element to be removed from this deque, if present 434 * @return {@code true} if the deque contained the specified element 435 */ 436 public boolean removeFirstOccurrence(Object o) { 437 if (o != null) { 438 final Object[] es = elements; 439 for (int i = head, end = tail, to = (i <= end) ? end : es.length; 440 ; i = 0, to = end) { 441 for (; i < to; i++) 442 if (o.equals(es[i])) { 443 delete(i); 444 return true; 445 } 446 if (to == end) break; 447 } 448 } 449 return false; 450 } 451 452 /** 453 * Removes the last occurrence of the specified element in this 454 * deque (when traversing the deque from head to tail). 455 * If the deque does not contain the element, it is unchanged. 456 * More formally, removes the last element {@code e} such that 457 * {@code o.equals(e)} (if such an element exists). 458 * Returns {@code true} if this deque contained the specified element 459 * (or equivalently, if this deque changed as a result of the call). 460 * 461 * @param o element to be removed from this deque, if present 462 * @return {@code true} if the deque contained the specified element 463 */ 464 public boolean removeLastOccurrence(Object o) { 465 if (o != null) { 466 final Object[] es = elements; 467 for (int i = tail, end = head, to = (i >= end) ? end : 0; 468 ; i = es.length, to = end) { 469 for (i--; i > to - 1; i--) 470 if (o.equals(es[i])) { 471 delete(i); 472 return true; 473 } 474 if (to == end) break; 475 } 476 } 477 return false; 478 } 479 480 // *** Queue methods *** 481 482 /** 483 * Inserts the specified element at the end of this deque. 484 * 485 * <p>This method is equivalent to {@link #addLast}. 486 * 487 * @param e the element to add 488 * @return {@code true} (as specified by {@link Collection#add}) 489 * @throws NullPointerException if the specified element is null 490 */ 491 public boolean add(E e) { 492 addLast(e); 493 return true; 494 } 495 496 /** 497 * Inserts the specified element at the end of this deque. 498 * 499 * <p>This method is equivalent to {@link #offerLast}. 500 * 501 * @param e the element to add 502 * @return {@code true} (as specified by {@link Queue#offer}) 503 * @throws NullPointerException if the specified element is null 504 */ 505 public boolean offer(E e) { 506 return offerLast(e); 507 } 508 509 /** 510 * Retrieves and removes the head of the queue represented by this deque. 511 * 512 * This method differs from {@link #poll poll} only in that it throws an 513 * exception if this deque is empty. 514 * 515 * <p>This method is equivalent to {@link #removeFirst}. 516 * 517 * @return the head of the queue represented by this deque 518 * @throws NoSuchElementException {@inheritDoc} 519 */ 520 public E remove() { 521 return removeFirst(); 522 } 523 524 /** 525 * Retrieves and removes the head of the queue represented by this deque 526 * (in other words, the first element of this deque), or returns 527 * {@code null} if this deque is empty. 528 * 529 * <p>This method is equivalent to {@link #pollFirst}. 530 * 531 * @return the head of the queue represented by this deque, or 532 * {@code null} if this deque is empty 533 */ 534 public E poll() { 535 return pollFirst(); 536 } 537 538 /** 539 * Retrieves, but does not remove, the head of the queue represented by 540 * this deque. This method differs from {@link #peek peek} only in 541 * that it throws an exception if this deque is empty. 542 * 543 * <p>This method is equivalent to {@link #getFirst}. 544 * 545 * @return the head of the queue represented by this deque 546 * @throws NoSuchElementException {@inheritDoc} 547 */ 548 public E element() { 549 return getFirst(); 550 } 551 552 /** 553 * Retrieves, but does not remove, the head of the queue represented by 554 * this deque, or returns {@code null} if this deque is empty. 555 * 556 * <p>This method is equivalent to {@link #peekFirst}. 557 * 558 * @return the head of the queue represented by this deque, or 559 * {@code null} if this deque is empty 560 */ 561 public E peek() { 562 return peekFirst(); 563 } 564 565 // *** Stack methods *** 566 567 /** 568 * Pushes an element onto the stack represented by this deque. In other 569 * words, inserts the element at the front of this deque. 570 * 571 * <p>This method is equivalent to {@link #addFirst}. 572 * 573 * @param e the element to push 574 * @throws NullPointerException if the specified element is null 575 */ 576 public void push(E e) { 577 addFirst(e); 578 } 579 580 /** 581 * Pops an element from the stack represented by this deque. In other 582 * words, removes and returns the first element of this deque. 583 * 584 * <p>This method is equivalent to {@link #removeFirst()}. 585 * 586 * @return the element at the front of this deque (which is the top 587 * of the stack represented by this deque) 588 * @throws NoSuchElementException {@inheritDoc} 589 */ 590 public E pop() { 591 return removeFirst(); 592 } 593 594 /** 595 * Removes the element at the specified position in the elements array. 596 * This can result in forward or backwards motion of array elements. 597 * We optimize for least element motion. 598 * 599 * <p>This method is called delete rather than remove to emphasize 600 * that its semantics differ from those of {@link List#remove(int)}. 601 * 602 * @return true if elements near tail moved backwards 603 */ 604 boolean delete(int i) { 605 final Object[] es = elements; 606 final int capacity = es.length; 607 final int h, t; 608 // number of elements before to-be-deleted elt 609 final int front = sub(i, h = head, capacity); 610 // number of elements after to-be-deleted elt 611 final int back = sub(t = tail, i, capacity) - 1; 612 if (front < back) { 613 // move front elements forwards 614 if (h <= i) { 615 System.arraycopy(es, h, es, h + 1, front); 616 } else { // Wrap around 617 System.arraycopy(es, 0, es, 1, i); 618 es[0] = es[capacity - 1]; 619 System.arraycopy(es, h, es, h + 1, front - (i + 1)); 620 } 621 es[h] = null; 622 head = inc(h, capacity); 623 return false; 624 } else { 625 // move back elements backwards 626 tail = dec(t, capacity); 627 if (i <= tail) { 628 System.arraycopy(es, i + 1, es, i, back); 629 } else { // Wrap around 630 System.arraycopy(es, i + 1, es, i, capacity - (i + 1)); 631 es[capacity - 1] = es[0]; 632 System.arraycopy(es, 1, es, 0, t - 1); 633 } 634 es[tail] = null; 635 return true; 636 } 637 } 638 639 // *** Collection Methods *** 640 641 /** 642 * Returns the number of elements in this deque. 643 * 644 * @return the number of elements in this deque 645 */ 646 public int size() { 647 return sub(tail, head, elements.length); 648 } 649 650 /** 651 * Returns {@code true} if this deque contains no elements. 652 * 653 * @return {@code true} if this deque contains no elements 654 */ 655 public boolean isEmpty() { 656 return head == tail; 657 } 658 659 /** 660 * Returns an iterator over the elements in this deque. The elements 661 * will be ordered from first (head) to last (tail). This is the same 662 * order that elements would be dequeued (via successive calls to 663 * {@link #remove} or popped (via successive calls to {@link #pop}). 664 * 665 * @return an iterator over the elements in this deque 666 */ 667 public Iterator<E> iterator() { 668 return new DeqIterator(); 669 } 670 671 public Iterator<E> descendingIterator() { 672 return new DescendingIterator(); 673 } 674 675 private class DeqIterator implements Iterator<E> { 676 /** Index of element to be returned by subsequent call to next. */ 677 int cursor; 678 679 /** Number of elements yet to be returned. */ 680 int remaining = size(); 681 682 /** 683 * Index of element returned by most recent call to next. 684 * Reset to -1 if element is deleted by a call to remove. 685 */ 686 int lastRet = -1; 687 688 DeqIterator() { cursor = head; } 689 690 public final boolean hasNext() { 691 return remaining > 0; 692 } 693 694 public E next() { 695 if (remaining <= 0) 696 throw new NoSuchElementException(); 697 final Object[] es = elements; 698 E e = nonNullElementAt(es, cursor); 699 cursor = inc(lastRet = cursor, es.length); 700 remaining--; 701 return e; 702 } 703 704 void postDelete(boolean leftShifted) { 705 if (leftShifted) 706 cursor = dec(cursor, elements.length); 707 } 708 709 public final void remove() { 710 if (lastRet < 0) 711 throw new IllegalStateException(); 712 postDelete(delete(lastRet)); 713 lastRet = -1; 714 } 715 716 public void forEachRemaining(Consumer<? super E> action) { 717 Objects.requireNonNull(action); 718 int r; 719 if ((r = remaining) <= 0) 720 return; 721 remaining = 0; 722 final Object[] es = elements; 723 if (es[cursor] == null || sub(tail, cursor, es.length) != r) 724 throw new ConcurrentModificationException(); 725 for (int i = cursor, end = tail, to = (i <= end) ? end : es.length; 726 ; i = 0, to = end) { 727 for (; i < to; i++) 728 action.accept(elementAt(es, i)); 729 if (to == end) { 730 if (end != tail) 731 throw new ConcurrentModificationException(); 732 lastRet = dec(end, es.length); 733 break; 734 } 735 } 736 } 737 } 738 739 private class DescendingIterator extends DeqIterator { 740 DescendingIterator() { cursor = dec(tail, elements.length); } 741 742 public final E next() { 743 if (remaining <= 0) 744 throw new NoSuchElementException(); 745 final Object[] es = elements; 746 E e = nonNullElementAt(es, cursor); 747 cursor = dec(lastRet = cursor, es.length); 748 remaining--; 749 return e; 750 } 751 752 void postDelete(boolean leftShifted) { 753 if (!leftShifted) 754 cursor = inc(cursor, elements.length); 755 } 756 757 public final void forEachRemaining(Consumer<? super E> action) { 758 Objects.requireNonNull(action); 759 int r; 760 if ((r = remaining) <= 0) 761 return; 762 remaining = 0; 763 final Object[] es = elements; 764 if (es[cursor] == null || sub(cursor, head, es.length) + 1 != r) 765 throw new ConcurrentModificationException(); 766 for (int i = cursor, end = head, to = (i >= end) ? end : 0; 767 ; i = es.length - 1, to = end) { 768 // hotspot generates faster code than for: i >= to ! 769 for (; i > to - 1; i--) 770 action.accept(elementAt(es, i)); 771 if (to == end) { 772 if (end != head) 773 throw new ConcurrentModificationException(); 774 lastRet = end; 775 break; 776 } 777 } 778 } 779 } 780 781 /** 782 * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em> 783 * and <em>fail-fast</em> {@link Spliterator} over the elements in this 784 * deque. 785 * 786 * <p>The {@code Spliterator} reports {@link Spliterator#SIZED}, 787 * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and 788 * {@link Spliterator#NONNULL}. Overriding implementations should document 789 * the reporting of additional characteristic values. 790 * 791 * @return a {@code Spliterator} over the elements in this deque 792 * @since 1.8 793 */ 794 public Spliterator<E> spliterator() { 795 return new DeqSpliterator(); 796 } 797 798 final class DeqSpliterator implements Spliterator<E> { 799 private int fence; // -1 until first use 800 private int cursor; // current index, modified on traverse/split 801 802 /** Constructs late-binding spliterator over all elements. */ 803 DeqSpliterator() { 804 this.fence = -1; 805 } 806 807 /** Constructs spliterator over the given range. */ 808 DeqSpliterator(int origin, int fence) { 809 // assert 0 <= origin && origin < elements.length; 810 // assert 0 <= fence && fence < elements.length; 811 this.cursor = origin; 812 this.fence = fence; 813 } 814 815 /** Ensures late-binding initialization; then returns fence. */ 816 private int getFence() { // force initialization 817 int t; 818 if ((t = fence) < 0) { 819 t = fence = tail; 820 cursor = head; 821 } 822 return t; 823 } 824 825 public DeqSpliterator trySplit() { 826 final Object[] es = elements; 827 final int i, n; 828 return ((n = sub(getFence(), i = cursor, es.length) >> 1) <= 0) 829 ? null 830 : new DeqSpliterator(i, cursor = add(i, n, es.length)); 831 } 832 833 public void forEachRemaining(Consumer<? super E> action) { 834 if (action == null) 835 throw new NullPointerException(); 836 final int end = getFence(), cursor = this.cursor; 837 final Object[] es = elements; 838 if (cursor != end) { 839 this.cursor = end; 840 // null check at both ends of range is sufficient 841 if (es[cursor] == null || es[dec(end, es.length)] == null) 842 throw new ConcurrentModificationException(); 843 for (int i = cursor, to = (i <= end) ? end : es.length; 844 ; i = 0, to = end) { 845 for (; i < to; i++) 846 action.accept(elementAt(es, i)); 847 if (to == end) break; 848 } 849 } 850 } 851 852 public boolean tryAdvance(Consumer<? super E> action) { 853 Objects.requireNonNull(action); 854 final Object[] es = elements; 855 if (fence < 0) { fence = tail; cursor = head; } // late-binding 856 final int i; 857 if ((i = cursor) == fence) 858 return false; 859 E e = nonNullElementAt(es, i); 860 cursor = inc(i, es.length); 861 action.accept(e); 862 return true; 863 } 864 865 public long estimateSize() { 866 return sub(getFence(), cursor, elements.length); 867 } 868 869 public int characteristics() { 870 return Spliterator.NONNULL 871 | Spliterator.ORDERED 872 | Spliterator.SIZED 873 | Spliterator.SUBSIZED; 874 } 875 } 876 877 /** 878 * @throws NullPointerException {@inheritDoc} 879 * @since 9 880 */ 881 public void forEach(Consumer<? super E> action) { 882 Objects.requireNonNull(action); 883 final Object[] es = elements; 884 for (int i = head, end = tail, to = (i <= end) ? end : es.length; 885 ; i = 0, to = end) { 886 for (; i < to; i++) 887 action.accept(elementAt(es, i)); 888 if (to == end) { 889 if (end != tail) throw new ConcurrentModificationException(); 890 break; 891 } 892 } 893 } 894 895 /** 896 * @throws NullPointerException {@inheritDoc} 897 * @since 9 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 * @since 9 907 */ 908 public boolean removeAll(Collection<?> c) { 909 Objects.requireNonNull(c); 910 return bulkRemove(e -> c.contains(e)); 911 } 912 913 /** 914 * @throws NullPointerException {@inheritDoc} 915 * @since 9 916 */ 917 public boolean retainAll(Collection<?> c) { 918 Objects.requireNonNull(c); 919 return bulkRemove(e -> !c.contains(e)); 920 } 921 922 /** Implementation of bulk remove methods. */ 923 private boolean bulkRemove(Predicate<? super E> filter) { 924 final Object[] es = elements; 925 // Optimize for initial run of survivors 926 for (int i = head, end = tail, to = (i <= end) ? end : es.length; 927 ; i = 0, to = end) { 928 for (; i < to; i++) 929 if (filter.test(elementAt(es, i))) 930 return bulkRemoveModified(filter, i); 931 if (to == end) { 932 if (end != tail) throw new ConcurrentModificationException(); 933 break; 934 } 935 } 936 return false; 937 } 938 939 // A tiny bit set implementation 940 941 private static long[] nBits(int n) { 942 return new long[((n - 1) >> 6) + 1]; 943 } 944 private static void setBit(long[] bits, int i) { 945 bits[i >> 6] |= 1L << i; 946 } 947 private static boolean isClear(long[] bits, int i) { 948 return (bits[i >> 6] & (1L << i)) == 0; 949 } 950 951 /** 952 * Helper for bulkRemove, in case of at least one deletion. 953 * Tolerate predicates that reentrantly access the collection for 954 * read (but writers still get CME), so traverse once to find 955 * elements to delete, a second pass to physically expunge. 956 * 957 * @param beg valid index of first element to be deleted 958 */ 959 private boolean bulkRemoveModified( 960 Predicate<? super E> filter, final int beg) { 961 final Object[] es = elements; 962 final int capacity = es.length; 963 final int end = tail; 964 final long[] deathRow = nBits(sub(end, beg, capacity)); 965 deathRow[0] = 1L; // set bit 0 966 for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg; 967 ; i = 0, to = end, k -= capacity) { 968 for (; i < to; i++) 969 if (filter.test(elementAt(es, i))) 970 setBit(deathRow, i - k); 971 if (to == end) break; 972 } 973 // a two-finger traversal, with hare i reading, tortoise w writing 974 int w = beg; 975 for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg; 976 ; w = 0) { // w rejoins i on second leg 977 // In this loop, i and w are on the same leg, with i > w 978 for (; i < to; i++) 979 if (isClear(deathRow, i - k)) 980 es[w++] = es[i]; 981 if (to == end) break; 982 // In this loop, w is on the first leg, i on the second 983 for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++) 984 if (isClear(deathRow, i - k)) 985 es[w++] = es[i]; 986 if (i >= to) { 987 if (w == capacity) w = 0; // "corner" case 988 break; 989 } 990 } 991 if (end != tail) throw new ConcurrentModificationException(); 992 circularClear(es, tail = w, end); 993 return true; 994 } 995 996 /** 997 * Returns {@code true} if this deque contains the specified element. 998 * More formally, returns {@code true} if and only if this deque contains 999 * at least one element {@code e} such that {@code o.equals(e)}. 1000 * 1001 * @param o object to be checked for containment in this deque 1002 * @return {@code true} if this deque contains the specified element 1003 */ 1004 public boolean contains(Object o) { 1005 if (o != null) { 1006 final Object[] es = elements; 1007 for (int i = head, end = tail, to = (i <= end) ? end : es.length; 1008 ; i = 0, to = end) { 1009 for (; i < to; i++) 1010 if (o.equals(es[i])) 1011 return true; 1012 if (to == end) break; 1013 } 1014 } 1015 return false; 1016 } 1017 1018 /** 1019 * Removes a single instance of the specified element from this deque. 1020 * If the deque does not contain the element, it is unchanged. 1021 * More formally, removes the first element {@code e} such that 1022 * {@code o.equals(e)} (if such an element exists). 1023 * Returns {@code true} if this deque contained the specified element 1024 * (or equivalently, if this deque changed as a result of the call). 1025 * 1026 * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}. 1027 * 1028 * @param o element to be removed from this deque, if present 1029 * @return {@code true} if this deque contained the specified element 1030 */ 1031 public boolean remove(Object o) { 1032 return removeFirstOccurrence(o); 1033 } 1034 1035 /** 1036 * Removes all of the elements from this deque. 1037 * The deque will be empty after this call returns. 1038 */ 1039 public void clear() { 1040 circularClear(elements, head, tail); 1041 head = tail = 0; 1042 } 1043 1044 /** 1045 * Nulls out slots starting at array index i, upto index end. 1046 * Condition i == end means "empty" - nothing to do. 1047 */ 1048 private static void circularClear(Object[] es, int i, int end) { 1049 // assert 0 <= i && i < es.length; 1050 // assert 0 <= end && end < es.length; 1051 for (int to = (i <= end) ? end : es.length; 1052 ; i = 0, to = end) { 1053 for (; i < to; i++) es[i] = null; 1054 if (to == end) break; 1055 } 1056 } 1057 1058 /** 1059 * Returns an array containing all of the elements in this deque 1060 * in proper sequence (from first to last element). 1061 * 1062 * <p>The returned array will be "safe" in that no references to it are 1063 * maintained by this deque. (In other words, this method must allocate 1064 * a new array). The caller is thus free to modify the returned array. 1065 * 1066 * <p>This method acts as bridge between array-based and collection-based 1067 * APIs. 1068 * 1069 * @return an array containing all of the elements in this deque 1070 */ 1071 public Object[] toArray() { 1072 return toArray(Object[].class); 1073 } 1074 1075 private <T> T[] toArray(Class<T[]> klazz) { 1076 final Object[] es = elements; 1077 final T[] a; 1078 final int head = this.head, tail = this.tail, end; 1079 if ((end = tail + ((head <= tail) ? 0 : es.length)) >= 0) { 1080 // Uses null extension feature of copyOfRange 1081 a = Arrays.copyOfRange(es, head, end, klazz); 1082 } else { 1083 // integer overflow! 1084 a = Arrays.copyOfRange(es, 0, end - head, klazz); 1085 System.arraycopy(es, head, a, 0, es.length - head); 1086 } 1087 if (end != tail) 1088 System.arraycopy(es, 0, a, es.length - head, tail); 1089 return a; 1090 } 1091 1092 /** 1093 * Returns an array containing all of the elements in this deque in 1094 * proper sequence (from first to last element); the runtime type of the 1095 * returned array is that of the specified array. If the deque fits in 1096 * the specified array, it is returned therein. Otherwise, a new array 1097 * is allocated with the runtime type of the specified array and the 1098 * size of this deque. 1099 * 1100 * <p>If this deque fits in the specified array with room to spare 1101 * (i.e., the array has more elements than this deque), the element in 1102 * the array immediately following the end of the deque is set to 1103 * {@code null}. 1104 * 1105 * <p>Like the {@link #toArray()} method, this method acts as bridge between 1106 * array-based and collection-based APIs. Further, this method allows 1107 * precise control over the runtime type of the output array, and may, 1108 * under certain circumstances, be used to save allocation costs. 1109 * 1110 * <p>Suppose {@code x} is a deque known to contain only strings. 1111 * The following code can be used to dump the deque into a newly 1112 * allocated array of {@code String}: 1113 * 1114 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre> 1115 * 1116 * Note that {@code toArray(new Object[0])} is identical in function to 1117 * {@code toArray()}. 1118 * 1119 * @param a the array into which the elements of the deque are to 1120 * be stored, if it is big enough; otherwise, a new array of the 1121 * same runtime type is allocated for this purpose 1122 * @return an array containing all of the elements in this deque 1123 * @throws ArrayStoreException if the runtime type of the specified array 1124 * is not a supertype of the runtime type of every element in 1125 * this deque 1126 * @throws NullPointerException if the specified array is null 1127 */ 1128 @SuppressWarnings("unchecked") 1129 public <T> T[] toArray(T[] a) { 1130 final int size; 1131 if ((size = size()) > a.length) 1132 return toArray((Class<T[]>) a.getClass()); 1133 final Object[] es = elements; 1134 for (int i = head, j = 0, len = Math.min(size, es.length - i); 1135 ; i = 0, len = tail) { 1136 System.arraycopy(es, i, a, j, len); 1137 if ((j += len) == size) break; 1138 } 1139 if (size < a.length) 1140 a[size] = null; 1141 return a; 1142 } 1143 1144 // *** Object methods *** 1145 1146 /** 1147 * Returns a copy of this deque. 1148 * 1149 * @return a copy of this deque 1150 */ 1151 public ArrayDeque<E> clone() { 1152 try { 1153 @SuppressWarnings("unchecked") 1154 ArrayDeque<E> result = (ArrayDeque<E>) super.clone(); 1155 result.elements = Arrays.copyOf(elements, elements.length); 1156 return result; 1157 } catch (CloneNotSupportedException e) { 1158 throw new AssertionError(); 1159 } 1160 } 1161 1162 private static final long serialVersionUID = 2340985798034038923L; 1163 1164 /** 1165 * Saves this deque to a stream (that is, serializes it). 1166 * 1167 * @param s the stream 1168 * @throws java.io.IOException if an I/O error occurs 1169 * @serialData The current size ({@code int}) of the deque, 1170 * followed by all of its elements (each an object reference) in 1171 * first-to-last order. 1172 */ 1173 private void writeObject(java.io.ObjectOutputStream s) 1174 throws java.io.IOException { 1175 s.defaultWriteObject(); 1176 1177 // Write out size 1178 s.writeInt(size()); 1179 1180 // Write out elements in order. 1181 final Object[] es = elements; 1182 for (int i = head, end = tail, to = (i <= end) ? end : es.length; 1183 ; i = 0, to = end) { 1184 for (; i < to; i++) 1185 s.writeObject(es[i]); 1186 if (to == end) break; 1187 } 1188 } 1189 1190 /** 1191 * Reconstitutes this deque from a stream (that is, deserializes it). 1192 * @param s the stream 1193 * @throws ClassNotFoundException if the class of a serialized object 1194 * could not be found 1195 * @throws java.io.IOException if an I/O error occurs 1196 */ 1197 private void readObject(java.io.ObjectInputStream s) 1198 throws java.io.IOException, ClassNotFoundException { 1199 s.defaultReadObject(); 1200 1201 // Read in size and allocate array 1202 int size = s.readInt(); 1203 elements = new Object[size + 1]; 1204 this.tail = size; 1205 1206 // Read in all elements in the proper order. 1207 for (int i = 0; i < size; i++) 1208 elements[i] = s.readObject(); 1209 } 1210 1211 /** debugging */ 1212 void checkInvariants() { 1213 // Use head and tail fields with empty slot at tail strategy. 1214 // head == tail disambiguates to "empty". 1215 try { 1216 int capacity = elements.length; 1217 // assert 0 <= head && head < capacity; 1218 // assert 0 <= tail && tail < capacity; 1219 // assert capacity > 0; 1220 // assert size() < capacity; 1221 // assert head == tail || elements[head] != null; 1222 // assert elements[tail] == null; 1223 // assert head == tail || elements[dec(tail, capacity)] != null; 1224 } catch (Throwable t) { 1225 System.err.printf("head=%d tail=%d capacity=%d%n", 1226 head, tail, elements.length); 1227 System.err.printf("elements=%s%n", 1228 Arrays.toString(elements)); 1229 throw t; 1230 } 1231 } 1232 1233 }