ArrayDeque.java revision 3de87b847fa94cce9beaf5b225404c1bc7ec475f
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.*; 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 collection 85 */ 86public class ArrayDeque<E> extends AbstractCollection<E> 87 implements Deque<E>, Cloneable, java.io.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 private transient Object[] elements; 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 private 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 private 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 int h = head; 279 @SuppressWarnings("unchecked") 280 E result = (E) elements[h]; 281 // Element is null if deque empty 282 if (result == null) 283 return null; 284 elements[h] = null; // Must null out slot 285 head = (h + 1) & (elements.length - 1); 286 return result; 287 } 288 289 public E pollLast() { 290 int t = (tail - 1) & (elements.length - 1); 291 @SuppressWarnings("unchecked") 292 E result = (E) elements[t]; 293 if (result == null) 294 return null; 295 elements[t] = null; 296 tail = t; 297 return result; 298 } 299 300 /** 301 * @throws NoSuchElementException {@inheritDoc} 302 */ 303 public E getFirst() { 304 @SuppressWarnings("unchecked") 305 E result = (E) elements[head]; 306 if (result == null) 307 throw new NoSuchElementException(); 308 return result; 309 } 310 311 /** 312 * @throws NoSuchElementException {@inheritDoc} 313 */ 314 public E getLast() { 315 @SuppressWarnings("unchecked") 316 E result = (E) elements[(tail - 1) & (elements.length - 1)]; 317 if (result == null) 318 throw new NoSuchElementException(); 319 return result; 320 } 321 322 @SuppressWarnings("unchecked") 323 public E peekFirst() { 324 // elements[head] is null if deque empty 325 return (E) elements[head]; 326 } 327 328 @SuppressWarnings("unchecked") 329 public E peekLast() { 330 return (E) elements[(tail - 1) & (elements.length - 1)]; 331 } 332 333 /** 334 * Removes the first occurrence of the specified element in this 335 * deque (when traversing the deque from head to tail). 336 * If the deque does not contain the element, it is unchanged. 337 * More formally, removes the first element {@code e} such that 338 * {@code o.equals(e)} (if such an element exists). 339 * Returns {@code true} if this deque contained the specified element 340 * (or equivalently, if this deque changed as a result of the call). 341 * 342 * @param o element to be removed from this deque, if present 343 * @return {@code true} if the deque contained the specified element 344 */ 345 public boolean removeFirstOccurrence(Object o) { 346 if (o == null) 347 return false; 348 int mask = elements.length - 1; 349 int i = head; 350 Object x; 351 while ( (x = elements[i]) != null) { 352 if (o.equals(x)) { 353 delete(i); 354 return true; 355 } 356 i = (i + 1) & mask; 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 return false; 376 int mask = elements.length - 1; 377 int i = (tail - 1) & mask; 378 Object x; 379 while ( (x = elements[i]) != null) { 380 if (o.equals(x)) { 381 delete(i); 382 return true; 383 } 384 i = (i - 1) & mask; 385 } 386 return false; 387 } 388 389 // *** Queue methods *** 390 391 /** 392 * Inserts the specified element at the end of this deque. 393 * 394 * <p>This method is equivalent to {@link #addLast}. 395 * 396 * @param e the element to add 397 * @return {@code true} (as specified by {@link Collection#add}) 398 * @throws NullPointerException if the specified element is null 399 */ 400 public boolean add(E e) { 401 addLast(e); 402 return true; 403 } 404 405 /** 406 * Inserts the specified element at the end of this deque. 407 * 408 * <p>This method is equivalent to {@link #offerLast}. 409 * 410 * @param e the element to add 411 * @return {@code true} (as specified by {@link Queue#offer}) 412 * @throws NullPointerException if the specified element is null 413 */ 414 public boolean offer(E e) { 415 return offerLast(e); 416 } 417 418 /** 419 * Retrieves and removes the head of the queue represented by this deque. 420 * 421 * This method differs from {@link #poll poll} only in that it throws an 422 * exception if this deque is empty. 423 * 424 * <p>This method is equivalent to {@link #removeFirst}. 425 * 426 * @return the head of the queue represented by this deque 427 * @throws NoSuchElementException {@inheritDoc} 428 */ 429 public E remove() { 430 return removeFirst(); 431 } 432 433 /** 434 * Retrieves and removes the head of the queue represented by this deque 435 * (in other words, the first element of this deque), or returns 436 * {@code null} if this deque is empty. 437 * 438 * <p>This method is equivalent to {@link #pollFirst}. 439 * 440 * @return the head of the queue represented by this deque, or 441 * {@code null} if this deque is empty 442 */ 443 public E poll() { 444 return pollFirst(); 445 } 446 447 /** 448 * Retrieves, but does not remove, the head of the queue represented by 449 * this deque. This method differs from {@link #peek peek} only in 450 * that it throws an exception if this deque is empty. 451 * 452 * <p>This method is equivalent to {@link #getFirst}. 453 * 454 * @return the head of the queue represented by this deque 455 * @throws NoSuchElementException {@inheritDoc} 456 */ 457 public E element() { 458 return getFirst(); 459 } 460 461 /** 462 * Retrieves, but does not remove, the head of the queue represented by 463 * this deque, or returns {@code null} if this deque is empty. 464 * 465 * <p>This method is equivalent to {@link #peekFirst}. 466 * 467 * @return the head of the queue represented by this deque, or 468 * {@code null} if this deque is empty 469 */ 470 public E peek() { 471 return peekFirst(); 472 } 473 474 // *** Stack methods *** 475 476 /** 477 * Pushes an element onto the stack represented by this deque. In other 478 * words, inserts the element at the front of this deque. 479 * 480 * <p>This method is equivalent to {@link #addFirst}. 481 * 482 * @param e the element to push 483 * @throws NullPointerException if the specified element is null 484 */ 485 public void push(E e) { 486 addFirst(e); 487 } 488 489 /** 490 * Pops an element from the stack represented by this deque. In other 491 * words, removes and returns the first element of this deque. 492 * 493 * <p>This method is equivalent to {@link #removeFirst()}. 494 * 495 * @return the element at the front of this deque (which is the top 496 * of the stack represented by this deque) 497 * @throws NoSuchElementException {@inheritDoc} 498 */ 499 public E pop() { 500 return removeFirst(); 501 } 502 503 private void checkInvariants() { 504 // assert elements[tail] == null; 505 // assert head == tail ? elements[head] == null : 506 // (elements[head] != null && 507 // elements[(tail - 1) & (elements.length - 1)] != null); 508 // assert elements[(head - 1) & (elements.length - 1)] == null; 509 } 510 511 /** 512 * Removes the element at the specified position in the elements array, 513 * adjusting head and tail as necessary. This can result in motion of 514 * elements backwards or forwards in the array. 515 * 516 * <p>This method is called delete rather than remove to emphasize 517 * that its semantics differ from those of {@link List#remove(int)}. 518 * 519 * @return true if elements moved backwards 520 */ 521 private boolean delete(int i) { 522 //checkInvariants(); 523 final Object[] elements = this.elements; 524 final int mask = elements.length - 1; 525 final int h = head; 526 final int t = tail; 527 final int front = (i - h) & mask; 528 final int back = (t - i) & mask; 529 530 // Invariant: head <= i < tail mod circularity 531 if (front >= ((t - h) & mask)) 532 throw new ConcurrentModificationException(); 533 534 // Optimize for least element motion 535 if (front < back) { 536 if (h <= i) { 537 System.arraycopy(elements, h, elements, h + 1, front); 538 } else { // Wrap around 539 System.arraycopy(elements, 0, elements, 1, i); 540 elements[0] = elements[mask]; 541 System.arraycopy(elements, h, elements, h + 1, mask - h); 542 } 543 elements[h] = null; 544 head = (h + 1) & mask; 545 return false; 546 } else { 547 if (i < t) { // Copy the null tail as well 548 System.arraycopy(elements, i + 1, elements, i, back); 549 tail = t - 1; 550 } else { // Wrap around 551 System.arraycopy(elements, i + 1, elements, i, mask - i); 552 elements[mask] = elements[0]; 553 System.arraycopy(elements, 1, elements, 0, t); 554 tail = (t - 1) & mask; 555 } 556 return true; 557 } 558 } 559 560 // *** Collection Methods *** 561 562 /** 563 * Returns the number of elements in this deque. 564 * 565 * @return the number of elements in this deque 566 */ 567 public int size() { 568 return (tail - head) & (elements.length - 1); 569 } 570 571 /** 572 * Returns {@code true} if this deque contains no elements. 573 * 574 * @return {@code true} if this deque contains no elements 575 */ 576 public boolean isEmpty() { 577 return head == tail; 578 } 579 580 /** 581 * Returns an iterator over the elements in this deque. The elements 582 * will be ordered from first (head) to last (tail). This is the same 583 * order that elements would be dequeued (via successive calls to 584 * {@link #remove} or popped (via successive calls to {@link #pop}). 585 * 586 * @return an iterator over the elements in this deque 587 */ 588 public Iterator<E> iterator() { 589 return new DeqIterator(); 590 } 591 592 public Iterator<E> descendingIterator() { 593 return new DescendingIterator(); 594 } 595 596 private class DeqIterator implements Iterator<E> { 597 /** 598 * Index of element to be returned by subsequent call to next. 599 */ 600 private int cursor = head; 601 602 /** 603 * Tail recorded at construction (also in remove), to stop 604 * iterator and also to check for comodification. 605 */ 606 private int fence = tail; 607 608 /** 609 * Index of element returned by most recent call to next. 610 * Reset to -1 if element is deleted by a call to remove. 611 */ 612 private int lastRet = -1; 613 614 public boolean hasNext() { 615 return cursor != fence; 616 } 617 618 public E next() { 619 if (cursor == fence) 620 throw new NoSuchElementException(); 621 @SuppressWarnings("unchecked") 622 E result = (E) elements[cursor]; 623 // This check doesn't catch all possible comodifications, 624 // but does catch the ones that corrupt traversal 625 if (tail != fence || result == null) 626 throw new ConcurrentModificationException(); 627 lastRet = cursor; 628 cursor = (cursor + 1) & (elements.length - 1); 629 return result; 630 } 631 632 public void remove() { 633 if (lastRet < 0) 634 throw new IllegalStateException(); 635 if (delete(lastRet)) { // if left-shifted, undo increment in next() 636 cursor = (cursor - 1) & (elements.length - 1); 637 fence = tail; 638 } 639 lastRet = -1; 640 } 641 642 @Override 643 public void forEachRemaining(Consumer<? super E> action) { 644 Objects.requireNonNull(action); 645 Object[] a = elements; 646 int m = a.length - 1, f = fence, i = cursor; 647 cursor = f; 648 while (i != f) { 649 @SuppressWarnings("unchecked") E e = (E)a[i]; 650 i = (i + 1) & m; 651 // Android-note: This uses a different heuristic for detecting 652 // concurrent modification exceptions than next(). As such, this is a less 653 // precise test. 654 if (e == null) 655 throw new ConcurrentModificationException(); 656 action.accept(e); 657 } 658 } 659 } 660 661 /** 662 * This class is nearly a mirror-image of DeqIterator, using tail 663 * instead of head for initial cursor, and head instead of tail 664 * for fence. 665 */ 666 private class DescendingIterator implements Iterator<E> { 667 private int cursor = tail; 668 private int fence = head; 669 private int lastRet = -1; 670 671 public boolean hasNext() { 672 return cursor != fence; 673 } 674 675 public E next() { 676 if (cursor == fence) 677 throw new NoSuchElementException(); 678 cursor = (cursor - 1) & (elements.length - 1); 679 @SuppressWarnings("unchecked") 680 E result = (E) elements[cursor]; 681 if (head != fence || result == null) 682 throw new ConcurrentModificationException(); 683 lastRet = cursor; 684 return result; 685 } 686 687 public void remove() { 688 if (lastRet < 0) 689 throw new IllegalStateException(); 690 if (!delete(lastRet)) { 691 cursor = (cursor + 1) & (elements.length - 1); 692 fence = head; 693 } 694 lastRet = -1; 695 } 696 } 697 698 /** 699 * Returns {@code true} if this deque contains the specified element. 700 * More formally, returns {@code true} if and only if this deque contains 701 * at least one element {@code e} such that {@code o.equals(e)}. 702 * 703 * @param o object to be checked for containment in this deque 704 * @return {@code true} if this deque contains the specified element 705 */ 706 public boolean contains(Object o) { 707 if (o == null) 708 return false; 709 int mask = elements.length - 1; 710 int i = head; 711 Object x; 712 while ( (x = elements[i]) != null) { 713 if (o.equals(x)) 714 return true; 715 i = (i + 1) & mask; 716 } 717 return false; 718 } 719 720 /** 721 * Removes a single instance of the specified element from this deque. 722 * If the deque does not contain the element, it is unchanged. 723 * More formally, removes the first element {@code e} such that 724 * {@code o.equals(e)} (if such an element exists). 725 * Returns {@code true} if this deque contained the specified element 726 * (or equivalently, if this deque changed as a result of the call). 727 * 728 * <p>This method is equivalent to {@link #removeFirstOccurrence}. 729 * 730 * @param o element to be removed from this deque, if present 731 * @return {@code true} if this deque contained the specified element 732 */ 733 public boolean remove(Object o) { 734 return removeFirstOccurrence(o); 735 } 736 737 /** 738 * Removes all of the elements from this deque. 739 * The deque will be empty after this call returns. 740 */ 741 public void clear() { 742 int h = head; 743 int t = tail; 744 if (h != t) { // clear all cells 745 head = tail = 0; 746 int i = h; 747 int mask = elements.length - 1; 748 do { 749 elements[i] = null; 750 i = (i + 1) & mask; 751 } while (i != t); 752 } 753 } 754 755 /** 756 * Returns an array containing all of the elements in this deque 757 * in proper sequence (from first to last element). 758 * 759 * <p>The returned array will be "safe" in that no references to it are 760 * maintained by this deque. (In other words, this method must allocate 761 * a new array). The caller is thus free to modify the returned array. 762 * 763 * <p>This method acts as bridge between array-based and collection-based 764 * APIs. 765 * 766 * @return an array containing all of the elements in this deque 767 */ 768 public Object[] toArray() { 769 final int head = this.head; 770 final int tail = this.tail; 771 boolean wrap = (tail < head); 772 int end = wrap ? tail + elements.length : tail; 773 Object[] a = Arrays.copyOfRange(elements, head, end); 774 if (wrap) 775 System.arraycopy(elements, 0, a, elements.length - head, tail); 776 return a; 777 } 778 779 /** 780 * Returns an array containing all of the elements in this deque in 781 * proper sequence (from first to last element); the runtime type of the 782 * returned array is that of the specified array. If the deque fits in 783 * the specified array, it is returned therein. Otherwise, a new array 784 * is allocated with the runtime type of the specified array and the 785 * size of this deque. 786 * 787 * <p>If this deque fits in the specified array with room to spare 788 * (i.e., the array has more elements than this deque), the element in 789 * the array immediately following the end of the deque is set to 790 * {@code null}. 791 * 792 * <p>Like the {@link #toArray()} method, this method acts as bridge between 793 * array-based and collection-based APIs. Further, this method allows 794 * precise control over the runtime type of the output array, and may, 795 * under certain circumstances, be used to save allocation costs. 796 * 797 * <p>Suppose {@code x} is a deque known to contain only strings. 798 * The following code can be used to dump the deque into a newly 799 * allocated array of {@code String}: 800 * 801 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre> 802 * 803 * Note that {@code toArray(new Object[0])} is identical in function to 804 * {@code toArray()}. 805 * 806 * @param a the array into which the elements of the deque are to 807 * be stored, if it is big enough; otherwise, a new array of the 808 * same runtime type is allocated for this purpose 809 * @return an array containing all of the elements in this deque 810 * @throws ArrayStoreException if the runtime type of the specified array 811 * is not a supertype of the runtime type of every element in 812 * this deque 813 * @throws NullPointerException if the specified array is null 814 */ 815 @SuppressWarnings("unchecked") 816 public <T> T[] toArray(T[] a) { 817 final int head = this.head; 818 final int tail = this.tail; 819 boolean wrap = (tail < head); 820 int size = (tail - head) + (wrap ? elements.length : 0); 821 int firstLeg = size - (wrap ? tail : 0); 822 int len = a.length; 823 if (size > len) { 824 a = (T[]) Arrays.copyOfRange(elements, head, head + size, 825 a.getClass()); 826 } else { 827 System.arraycopy(elements, head, a, 0, firstLeg); 828 if (size < len) 829 a[size] = null; 830 } 831 if (wrap) 832 System.arraycopy(elements, 0, a, firstLeg, tail); 833 return a; 834 } 835 836 // *** Object methods *** 837 838 /** 839 * Returns a copy of this deque. 840 * 841 * @return a copy of this deque 842 */ 843 public ArrayDeque<E> clone() { 844 try { 845 @SuppressWarnings("unchecked") 846 ArrayDeque<E> result = (ArrayDeque<E>) super.clone(); 847 result.elements = Arrays.copyOf(elements, elements.length); 848 return result; 849 } catch (CloneNotSupportedException e) { 850 throw new AssertionError(); 851 } 852 } 853 854 private static final long serialVersionUID = 2340985798034038923L; 855 856 /** 857 * Saves this deque to a stream (that is, serializes it). 858 * 859 * @serialData The current size ({@code int}) of the deque, 860 * followed by all of its elements (each an object reference) in 861 * first-to-last order. 862 */ 863 private void writeObject(java.io.ObjectOutputStream s) 864 throws java.io.IOException { 865 s.defaultWriteObject(); 866 867 // Write out size 868 s.writeInt(size()); 869 870 // Write out elements in order. 871 int mask = elements.length - 1; 872 for (int i = head; i != tail; i = (i + 1) & mask) 873 s.writeObject(elements[i]); 874 } 875 876 /** 877 * Reconstitutes this deque from a stream (that is, deserializes it). 878 */ 879 private void readObject(java.io.ObjectInputStream s) 880 throws java.io.IOException, ClassNotFoundException { 881 s.defaultReadObject(); 882 883 // Read in size and allocate array 884 int size = s.readInt(); 885 allocateElements(size); 886 head = 0; 887 tail = size; 888 889 // Read in all elements in the proper order. 890 for (int i = 0; i < size; i++) 891 elements[i] = s.readObject(); 892 } 893} 894