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