ArrayList.java revision 51b1b6997fd3f980076b8081f7f1165ccc2a4008
1/* 2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package java.util; 27 28/** 29 * Resizable-array implementation of the <tt>List</tt> interface. Implements 30 * all optional list operations, and permits all elements, including 31 * <tt>null</tt>. In addition to implementing the <tt>List</tt> interface, 32 * this class provides methods to manipulate the size of the array that is 33 * used internally to store the list. (This class is roughly equivalent to 34 * <tt>Vector</tt>, except that it is unsynchronized.) 35 * 36 * <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>, 37 * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant 38 * time. The <tt>add</tt> operation runs in <i>amortized constant time</i>, 39 * that is, adding n elements requires O(n) time. All of the other operations 40 * run in linear time (roughly speaking). The constant factor is low compared 41 * to that for the <tt>LinkedList</tt> implementation. 42 * 43 * <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is 44 * the size of the array used to store the elements in the list. It is always 45 * at least as large as the list size. As elements are added to an ArrayList, 46 * its capacity grows automatically. The details of the growth policy are not 47 * specified beyond the fact that adding an element has constant amortized 48 * time cost. 49 * 50 * <p>An application can increase the capacity of an <tt>ArrayList</tt> instance 51 * before adding a large number of elements using the <tt>ensureCapacity</tt> 52 * operation. This may reduce the amount of incremental reallocation. 53 * 54 * <p><strong>Note that this implementation is not synchronized.</strong> 55 * If multiple threads access an <tt>ArrayList</tt> instance concurrently, 56 * and at least one of the threads modifies the list structurally, it 57 * <i>must</i> be synchronized externally. (A structural modification is 58 * any operation that adds or deletes one or more elements, or explicitly 59 * resizes the backing array; merely setting the value of an element is not 60 * a structural modification.) This is typically accomplished by 61 * synchronizing on some object that naturally encapsulates the list. 62 * 63 * If no such object exists, the list should be "wrapped" using the 64 * {@link Collections#synchronizedList Collections.synchronizedList} 65 * method. This is best done at creation time, to prevent accidental 66 * unsynchronized access to the list:<pre> 67 * List list = Collections.synchronizedList(new ArrayList(...));</pre> 68 * 69 * <p><a name="fail-fast"/> 70 * The iterators returned by this class's {@link #iterator() iterator} and 71 * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>: 72 * if the list is structurally modified at any time after the iterator is 73 * created, in any way except through the iterator's own 74 * {@link ListIterator#remove() remove} or 75 * {@link ListIterator#add(Object) add} methods, the iterator will throw a 76 * {@link ConcurrentModificationException}. Thus, in the face of 77 * concurrent modification, the iterator fails quickly and cleanly, rather 78 * than risking arbitrary, non-deterministic behavior at an undetermined 79 * time in the future. 80 * 81 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed 82 * as it is, generally speaking, impossible to make any hard guarantees in the 83 * presence of unsynchronized concurrent modification. Fail-fast iterators 84 * throw {@code ConcurrentModificationException} on a best-effort basis. 85 * Therefore, it would be wrong to write a program that depended on this 86 * exception for its correctness: <i>the fail-fast behavior of iterators 87 * should be used only to detect bugs.</i> 88 * 89 * <p>This class is a member of the 90 * <a href="{@docRoot}/../technotes/guides/collections/index.html"> 91 * Java Collections Framework</a>. 92 * 93 * @author Josh Bloch 94 * @author Neal Gafter 95 * @see Collection 96 * @see List 97 * @see LinkedList 98 * @see Vector 99 * @since 1.2 100 */ 101 102public class ArrayList<E> extends AbstractList<E> 103 implements List<E>, RandomAccess, Cloneable, java.io.Serializable 104{ 105 private static final long serialVersionUID = 8683452581122892189L; 106 107 /** 108 * Default initial capacity. 109 */ 110 private static final int DEFAULT_CAPACITY = 10; 111 112 /** 113 * Shared empty array instance used for empty instances. 114 */ 115 private static final Object[] EMPTY_ELEMENTDATA = {}; 116 117 /** 118 * The array buffer into which the elements of the ArrayList are stored. 119 * The capacity of the ArrayList is the length of this array buffer. Any 120 * empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to 121 * DEFAULT_CAPACITY when the first element is added. 122 */ 123 private transient Object[] elementData; 124 125 /** 126 * The size of the ArrayList (the number of elements it contains). 127 * 128 * @serial 129 */ 130 private int size; 131 132 /** 133 * Constructs an empty list with the specified initial capacity. 134 * 135 * @param initialCapacity the initial capacity of the list 136 * @throws IllegalArgumentException if the specified initial capacity 137 * is negative 138 */ 139 public ArrayList(int initialCapacity) { 140 super(); 141 if (initialCapacity < 0) 142 throw new IllegalArgumentException("Illegal Capacity: "+ 143 initialCapacity); 144 this.elementData = new Object[initialCapacity]; 145 } 146 147 /** 148 * Constructs an empty list with an initial capacity of ten. 149 */ 150 public ArrayList() { 151 super(); 152 this.elementData = EMPTY_ELEMENTDATA; 153 } 154 155 /** 156 * Constructs a list containing the elements of the specified 157 * collection, in the order they are returned by the collection's 158 * iterator. 159 * 160 * @param c the collection whose elements are to be placed into this list 161 * @throws NullPointerException if the specified collection is null 162 */ 163 public ArrayList(Collection<? extends E> c) { 164 elementData = c.toArray(); 165 size = elementData.length; 166 // c.toArray might (incorrectly) not return Object[] (see 6260652) 167 if (elementData.getClass() != Object[].class) 168 elementData = Arrays.copyOf(elementData, size, Object[].class); 169 } 170 171 /** 172 * Trims the capacity of this <tt>ArrayList</tt> instance to be the 173 * list's current size. An application can use this operation to minimize 174 * the storage of an <tt>ArrayList</tt> instance. 175 */ 176 public void trimToSize() { 177 modCount++; 178 if (size < elementData.length) { 179 elementData = Arrays.copyOf(elementData, size); 180 } 181 } 182 183 /** 184 * Increases the capacity of this <tt>ArrayList</tt> instance, if 185 * necessary, to ensure that it can hold at least the number of elements 186 * specified by the minimum capacity argument. 187 * 188 * @param minCapacity the desired minimum capacity 189 */ 190 public void ensureCapacity(int minCapacity) { 191 int minExpand = (elementData != EMPTY_ELEMENTDATA) 192 // any size if real element table 193 ? 0 194 // larger than default for empty table. It's already supposed to be 195 // at default size. 196 : DEFAULT_CAPACITY; 197 198 if (minCapacity > minExpand) { 199 ensureExplicitCapacity(minCapacity); 200 } 201 } 202 203 private void ensureCapacityInternal(int minCapacity) { 204 if (elementData == EMPTY_ELEMENTDATA) { 205 minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); 206 } 207 208 ensureExplicitCapacity(minCapacity); 209 } 210 211 private void ensureExplicitCapacity(int minCapacity) { 212 modCount++; 213 214 // overflow-conscious code 215 if (minCapacity - elementData.length > 0) 216 grow(minCapacity); 217 } 218 219 /** 220 * The maximum size of array to allocate. 221 * Some VMs reserve some header words in an array. 222 * Attempts to allocate larger arrays may result in 223 * OutOfMemoryError: Requested array size exceeds VM limit 224 */ 225 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; 226 227 /** 228 * Increases the capacity to ensure that it can hold at least the 229 * number of elements specified by the minimum capacity argument. 230 * 231 * @param minCapacity the desired minimum capacity 232 */ 233 private void grow(int minCapacity) { 234 // overflow-conscious code 235 int oldCapacity = elementData.length; 236 int newCapacity = oldCapacity + (oldCapacity >> 1); 237 if (newCapacity - minCapacity < 0) 238 newCapacity = minCapacity; 239 if (newCapacity - MAX_ARRAY_SIZE > 0) 240 newCapacity = hugeCapacity(minCapacity); 241 // minCapacity is usually close to size, so this is a win: 242 elementData = Arrays.copyOf(elementData, newCapacity); 243 } 244 245 private static int hugeCapacity(int minCapacity) { 246 if (minCapacity < 0) // overflow 247 throw new OutOfMemoryError(); 248 return (minCapacity > MAX_ARRAY_SIZE) ? 249 Integer.MAX_VALUE : 250 MAX_ARRAY_SIZE; 251 } 252 253 /** 254 * Returns the number of elements in this list. 255 * 256 * @return the number of elements in this list 257 */ 258 public int size() { 259 return size; 260 } 261 262 /** 263 * Returns <tt>true</tt> if this list contains no elements. 264 * 265 * @return <tt>true</tt> if this list contains no elements 266 */ 267 public boolean isEmpty() { 268 return size == 0; 269 } 270 271 /** 272 * Returns <tt>true</tt> if this list contains the specified element. 273 * More formally, returns <tt>true</tt> if and only if this list contains 274 * at least one element <tt>e</tt> such that 275 * <tt>(o==null ? e==null : o.equals(e))</tt>. 276 * 277 * @param o element whose presence in this list is to be tested 278 * @return <tt>true</tt> if this list contains the specified element 279 */ 280 public boolean contains(Object o) { 281 return indexOf(o) >= 0; 282 } 283 284 /** 285 * Returns the index of the first occurrence of the specified element 286 * in this list, or -1 if this list does not contain the element. 287 * More formally, returns the lowest index <tt>i</tt> such that 288 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, 289 * or -1 if there is no such index. 290 */ 291 public int indexOf(Object o) { 292 if (o == null) { 293 for (int i = 0; i < size; i++) 294 if (elementData[i]==null) 295 return i; 296 } else { 297 for (int i = 0; i < size; i++) 298 if (o.equals(elementData[i])) 299 return i; 300 } 301 return -1; 302 } 303 304 /** 305 * Returns the index of the last occurrence of the specified element 306 * in this list, or -1 if this list does not contain the element. 307 * More formally, returns the highest index <tt>i</tt> such that 308 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, 309 * or -1 if there is no such index. 310 */ 311 public int lastIndexOf(Object o) { 312 if (o == null) { 313 for (int i = size-1; i >= 0; i--) 314 if (elementData[i]==null) 315 return i; 316 } else { 317 for (int i = size-1; i >= 0; i--) 318 if (o.equals(elementData[i])) 319 return i; 320 } 321 return -1; 322 } 323 324 /** 325 * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The 326 * elements themselves are not copied.) 327 * 328 * @return a clone of this <tt>ArrayList</tt> instance 329 */ 330 public Object clone() { 331 try { 332 @SuppressWarnings("unchecked") 333 ArrayList<E> v = (ArrayList<E>) super.clone(); 334 v.elementData = Arrays.copyOf(elementData, size); 335 v.modCount = 0; 336 return v; 337 } catch (CloneNotSupportedException e) { 338 // this shouldn't happen, since we are Cloneable 339 throw new InternalError(); 340 } 341 } 342 343 /** 344 * Returns an array containing all of the elements in this list 345 * in proper sequence (from first to last element). 346 * 347 * <p>The returned array will be "safe" in that no references to it are 348 * maintained by this list. (In other words, this method must allocate 349 * a new array). The caller is thus free to modify the returned array. 350 * 351 * <p>This method acts as bridge between array-based and collection-based 352 * APIs. 353 * 354 * @return an array containing all of the elements in this list in 355 * proper sequence 356 */ 357 public Object[] toArray() { 358 return Arrays.copyOf(elementData, size); 359 } 360 361 /** 362 * Returns an array containing all of the elements in this list in proper 363 * sequence (from first to last element); the runtime type of the returned 364 * array is that of the specified array. If the list fits in the 365 * specified array, it is returned therein. Otherwise, a new array is 366 * allocated with the runtime type of the specified array and the size of 367 * this list. 368 * 369 * <p>If the list fits in the specified array with room to spare 370 * (i.e., the array has more elements than the list), the element in 371 * the array immediately following the end of the collection is set to 372 * <tt>null</tt>. (This is useful in determining the length of the 373 * list <i>only</i> if the caller knows that the list does not contain 374 * any null elements.) 375 * 376 * @param a the array into which the elements of the list are to 377 * be stored, if it is big enough; otherwise, a new array of the 378 * same runtime type is allocated for this purpose. 379 * @return an array containing the elements of the list 380 * @throws ArrayStoreException if the runtime type of the specified array 381 * is not a supertype of the runtime type of every element in 382 * this list 383 * @throws NullPointerException if the specified array is null 384 */ 385 @SuppressWarnings("unchecked") 386 public <T> T[] toArray(T[] a) { 387 if (a.length < size) 388 // Make a new array of a's runtime type, but my contents: 389 return (T[]) Arrays.copyOf(elementData, size, a.getClass()); 390 System.arraycopy(elementData, 0, a, 0, size); 391 if (a.length > size) 392 a[size] = null; 393 return a; 394 } 395 396 // Positional Access Operations 397 398 @SuppressWarnings("unchecked") 399 E elementData(int index) { 400 return (E) elementData[index]; 401 } 402 403 /** 404 * Returns the element at the specified position in this list. 405 * 406 * @param index index of the element to return 407 * @return the element at the specified position in this list 408 * @throws IndexOutOfBoundsException {@inheritDoc} 409 */ 410 public E get(int index) { 411 rangeCheck(index); 412 413 return elementData(index); 414 } 415 416 /** 417 * Replaces the element at the specified position in this list with 418 * the specified element. 419 * 420 * @param index index of the element to replace 421 * @param element element to be stored at the specified position 422 * @return the element previously at the specified position 423 * @throws IndexOutOfBoundsException {@inheritDoc} 424 */ 425 public E set(int index, E element) { 426 rangeCheck(index); 427 428 E oldValue = elementData(index); 429 elementData[index] = element; 430 return oldValue; 431 } 432 433 /** 434 * Appends the specified element to the end of this list. 435 * 436 * @param e element to be appended to this list 437 * @return <tt>true</tt> (as specified by {@link Collection#add}) 438 */ 439 public boolean add(E e) { 440 ensureCapacityInternal(size + 1); // Increments modCount!! 441 elementData[size++] = e; 442 return true; 443 } 444 445 /** 446 * Inserts the specified element at the specified position in this 447 * list. Shifts the element currently at that position (if any) and 448 * any subsequent elements to the right (adds one to their indices). 449 * 450 * @param index index at which the specified element is to be inserted 451 * @param element element to be inserted 452 * @throws IndexOutOfBoundsException {@inheritDoc} 453 */ 454 public void add(int index, E element) { 455 rangeCheckForAdd(index); 456 457 ensureCapacityInternal(size + 1); // Increments modCount!! 458 System.arraycopy(elementData, index, elementData, index + 1, 459 size - index); 460 elementData[index] = element; 461 size++; 462 } 463 464 /** 465 * Removes the element at the specified position in this list. 466 * Shifts any subsequent elements to the left (subtracts one from their 467 * indices). 468 * 469 * @param index the index of the element to be removed 470 * @return the element that was removed from the list 471 * @throws IndexOutOfBoundsException {@inheritDoc} 472 */ 473 public E remove(int index) { 474 rangeCheck(index); 475 476 modCount++; 477 E oldValue = elementData(index); 478 479 int numMoved = size - index - 1; 480 if (numMoved > 0) 481 System.arraycopy(elementData, index+1, elementData, index, 482 numMoved); 483 elementData[--size] = null; // clear to let GC do its work 484 485 return oldValue; 486 } 487 488 /** 489 * Removes the first occurrence of the specified element from this list, 490 * if it is present. If the list does not contain the element, it is 491 * unchanged. More formally, removes the element with the lowest index 492 * <tt>i</tt> such that 493 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> 494 * (if such an element exists). Returns <tt>true</tt> if this list 495 * contained the specified element (or equivalently, if this list 496 * changed as a result of the call). 497 * 498 * @param o element to be removed from this list, if present 499 * @return <tt>true</tt> if this list contained the specified element 500 */ 501 public boolean remove(Object o) { 502 if (o == null) { 503 for (int index = 0; index < size; index++) 504 if (elementData[index] == null) { 505 fastRemove(index); 506 return true; 507 } 508 } else { 509 for (int index = 0; index < size; index++) 510 if (o.equals(elementData[index])) { 511 fastRemove(index); 512 return true; 513 } 514 } 515 return false; 516 } 517 518 /* 519 * Private remove method that skips bounds checking and does not 520 * return the value removed. 521 */ 522 private void fastRemove(int index) { 523 modCount++; 524 int numMoved = size - index - 1; 525 if (numMoved > 0) 526 System.arraycopy(elementData, index+1, elementData, index, 527 numMoved); 528 elementData[--size] = null; // clear to let GC do its work 529 } 530 531 /** 532 * Removes all of the elements from this list. The list will 533 * be empty after this call returns. 534 */ 535 public void clear() { 536 modCount++; 537 538 // clear to let GC do its work 539 for (int i = 0; i < size; i++) 540 elementData[i] = null; 541 542 size = 0; 543 } 544 545 /** 546 * Appends all of the elements in the specified collection to the end of 547 * this list, in the order that they are returned by the 548 * specified collection's Iterator. The behavior of this operation is 549 * undefined if the specified collection is modified while the operation 550 * is in progress. (This implies that the behavior of this call is 551 * undefined if the specified collection is this list, and this 552 * list is nonempty.) 553 * 554 * @param c collection containing elements to be added to this list 555 * @return <tt>true</tt> if this list changed as a result of the call 556 * @throws NullPointerException if the specified collection is null 557 */ 558 public boolean addAll(Collection<? extends E> c) { 559 Object[] a = c.toArray(); 560 int numNew = a.length; 561 ensureCapacityInternal(size + numNew); // Increments modCount 562 System.arraycopy(a, 0, elementData, size, numNew); 563 size += numNew; 564 return numNew != 0; 565 } 566 567 /** 568 * Inserts all of the elements in the specified collection into this 569 * list, starting at the specified position. Shifts the element 570 * currently at that position (if any) and any subsequent elements to 571 * the right (increases their indices). The new elements will appear 572 * in the list in the order that they are returned by the 573 * specified collection's iterator. 574 * 575 * @param index index at which to insert the first element from the 576 * specified collection 577 * @param c collection containing elements to be added to this list 578 * @return <tt>true</tt> if this list changed as a result of the call 579 * @throws IndexOutOfBoundsException {@inheritDoc} 580 * @throws NullPointerException if the specified collection is null 581 */ 582 public boolean addAll(int index, Collection<? extends E> c) { 583 rangeCheckForAdd(index); 584 585 Object[] a = c.toArray(); 586 int numNew = a.length; 587 ensureCapacityInternal(size + numNew); // Increments modCount 588 589 int numMoved = size - index; 590 if (numMoved > 0) 591 System.arraycopy(elementData, index, elementData, index + numNew, 592 numMoved); 593 594 System.arraycopy(a, 0, elementData, index, numNew); 595 size += numNew; 596 return numNew != 0; 597 } 598 599 /** 600 * Removes from this list all of the elements whose index is between 601 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. 602 * Shifts any succeeding elements to the left (reduces their index). 603 * This call shortens the list by {@code (toIndex - fromIndex)} elements. 604 * (If {@code toIndex==fromIndex}, this operation has no effect.) 605 * 606 * @throws IndexOutOfBoundsException if {@code fromIndex} or 607 * {@code toIndex} is out of range 608 * ({@code fromIndex < 0 || 609 * fromIndex >= size() || 610 * toIndex > size() || 611 * toIndex < fromIndex}) 612 */ 613 protected void removeRange(int fromIndex, int toIndex) { 614 modCount++; 615 int numMoved = size - toIndex; 616 System.arraycopy(elementData, toIndex, elementData, fromIndex, 617 numMoved); 618 619 // clear to let GC do its work 620 int newSize = size - (toIndex-fromIndex); 621 for (int i = newSize; i < size; i++) { 622 elementData[i] = null; 623 } 624 size = newSize; 625 } 626 627 /** 628 * Checks if the given index is in range. If not, throws an appropriate 629 * runtime exception. This method does *not* check if the index is 630 * negative: It is always used immediately prior to an array access, 631 * which throws an ArrayIndexOutOfBoundsException if index is negative. 632 */ 633 private void rangeCheck(int index) { 634 if (index >= size) 635 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 636 } 637 638 /** 639 * A version of rangeCheck used by add and addAll. 640 */ 641 private void rangeCheckForAdd(int index) { 642 if (index > size || index < 0) 643 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 644 } 645 646 /** 647 * Constructs an IndexOutOfBoundsException detail message. 648 * Of the many possible refactorings of the error handling code, 649 * this "outlining" performs best with both server and client VMs. 650 */ 651 private String outOfBoundsMsg(int index) { 652 return "Index: "+index+", Size: "+size; 653 } 654 655 /** 656 * Removes from this list all of its elements that are contained in the 657 * specified collection. 658 * 659 * @param c collection containing elements to be removed from this list 660 * @return {@code true} if this list changed as a result of the call 661 * @throws ClassCastException if the class of an element of this list 662 * is incompatible with the specified collection 663 * (<a href="Collection.html#optional-restrictions">optional</a>) 664 * @throws NullPointerException if this list contains a null element and the 665 * specified collection does not permit null elements 666 * (<a href="Collection.html#optional-restrictions">optional</a>), 667 * or if the specified collection is null 668 * @see Collection#contains(Object) 669 */ 670 public boolean removeAll(Collection<?> c) { 671 return batchRemove(c, false); 672 } 673 674 /** 675 * Retains only the elements in this list that are contained in the 676 * specified collection. In other words, removes from this list all 677 * of its elements that are not contained in the specified collection. 678 * 679 * @param c collection containing elements to be retained in this list 680 * @return {@code true} if this list changed as a result of the call 681 * @throws ClassCastException if the class of an element of this list 682 * is incompatible with the specified collection 683 * (<a href="Collection.html#optional-restrictions">optional</a>) 684 * @throws NullPointerException if this list contains a null element and the 685 * specified collection does not permit null elements 686 * (<a href="Collection.html#optional-restrictions">optional</a>), 687 * or if the specified collection is null 688 * @see Collection#contains(Object) 689 */ 690 public boolean retainAll(Collection<?> c) { 691 return batchRemove(c, true); 692 } 693 694 private boolean batchRemove(Collection<?> c, boolean complement) { 695 final Object[] elementData = this.elementData; 696 int r = 0, w = 0; 697 boolean modified = false; 698 try { 699 for (; r < size; r++) 700 if (c.contains(elementData[r]) == complement) 701 elementData[w++] = elementData[r]; 702 } finally { 703 // Preserve behavioral compatibility with AbstractCollection, 704 // even if c.contains() throws. 705 if (r != size) { 706 System.arraycopy(elementData, r, 707 elementData, w, 708 size - r); 709 w += size - r; 710 } 711 if (w != size) { 712 // clear to let GC do its work 713 for (int i = w; i < size; i++) 714 elementData[i] = null; 715 modCount += size - w; 716 size = w; 717 modified = true; 718 } 719 } 720 return modified; 721 } 722 723 /** 724 * Save the state of the <tt>ArrayList</tt> instance to a stream (that 725 * is, serialize it). 726 * 727 * @serialData The length of the array backing the <tt>ArrayList</tt> 728 * instance is emitted (int), followed by all of its elements 729 * (each an <tt>Object</tt>) in the proper order. 730 */ 731 private void writeObject(java.io.ObjectOutputStream s) 732 throws java.io.IOException{ 733 // Write out element count, and any hidden stuff 734 int expectedModCount = modCount; 735 s.defaultWriteObject(); 736 737 // Write out size as capacity for behavioural compatibility with clone() 738 s.writeInt(size); 739 740 // Write out all elements in the proper order. 741 for (int i=0; i<size; i++) { 742 s.writeObject(elementData[i]); 743 } 744 745 if (modCount != expectedModCount) { 746 throw new ConcurrentModificationException(); 747 } 748 } 749 750 /** 751 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, 752 * deserialize it). 753 */ 754 private void readObject(java.io.ObjectInputStream s) 755 throws java.io.IOException, ClassNotFoundException { 756 elementData = EMPTY_ELEMENTDATA; 757 758 // Read in size, and any hidden stuff 759 s.defaultReadObject(); 760 761 // Read in capacity 762 s.readInt(); // ignored 763 764 if (size > 0) { 765 // be like clone(), allocate array based upon size not capacity 766 ensureCapacityInternal(size); 767 768 Object[] a = elementData; 769 // Read in all elements in the proper order. 770 for (int i=0; i<size; i++) { 771 a[i] = s.readObject(); 772 } 773 } 774 } 775 776 /** 777 * Returns a list iterator over the elements in this list (in proper 778 * sequence), starting at the specified position in the list. 779 * The specified index indicates the first element that would be 780 * returned by an initial call to {@link ListIterator#next next}. 781 * An initial call to {@link ListIterator#previous previous} would 782 * return the element with the specified index minus one. 783 * 784 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 785 * 786 * @throws IndexOutOfBoundsException {@inheritDoc} 787 */ 788 public ListIterator<E> listIterator(int index) { 789 if (index < 0 || index > size) 790 throw new IndexOutOfBoundsException("Index: "+index); 791 return new ListItr(index); 792 } 793 794 /** 795 * Returns a list iterator over the elements in this list (in proper 796 * sequence). 797 * 798 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 799 * 800 * @see #listIterator(int) 801 */ 802 public ListIterator<E> listIterator() { 803 return new ListItr(0); 804 } 805 806 /** 807 * Returns an iterator over the elements in this list in proper sequence. 808 * 809 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 810 * 811 * @return an iterator over the elements in this list in proper sequence 812 */ 813 public Iterator<E> iterator() { 814 return new Itr(); 815 } 816 817 /** 818 * An optimized version of AbstractList.Itr 819 */ 820 private class Itr implements Iterator<E> { 821 int cursor; // index of next element to return 822 int lastRet = -1; // index of last element returned; -1 if no such 823 int expectedModCount = modCount; 824 825 public boolean hasNext() { 826 return cursor != size; 827 } 828 829 @SuppressWarnings("unchecked") 830 public E next() { 831 checkForComodification(); 832 int i = cursor; 833 if (i >= size) 834 throw new NoSuchElementException(); 835 Object[] elementData = ArrayList.this.elementData; 836 if (i >= elementData.length) 837 throw new ConcurrentModificationException(); 838 cursor = i + 1; 839 return (E) elementData[lastRet = i]; 840 } 841 842 public void remove() { 843 if (lastRet < 0) 844 throw new IllegalStateException(); 845 checkForComodification(); 846 847 try { 848 ArrayList.this.remove(lastRet); 849 cursor = lastRet; 850 lastRet = -1; 851 expectedModCount = modCount; 852 } catch (IndexOutOfBoundsException ex) { 853 throw new ConcurrentModificationException(); 854 } 855 } 856 857 final void checkForComodification() { 858 if (modCount != expectedModCount) 859 throw new ConcurrentModificationException(); 860 } 861 } 862 863 /** 864 * An optimized version of AbstractList.ListItr 865 */ 866 private class ListItr extends Itr implements ListIterator<E> { 867 ListItr(int index) { 868 super(); 869 cursor = index; 870 } 871 872 public boolean hasPrevious() { 873 return cursor != 0; 874 } 875 876 public int nextIndex() { 877 return cursor; 878 } 879 880 public int previousIndex() { 881 return cursor - 1; 882 } 883 884 @SuppressWarnings("unchecked") 885 public E previous() { 886 checkForComodification(); 887 int i = cursor - 1; 888 if (i < 0) 889 throw new NoSuchElementException(); 890 Object[] elementData = ArrayList.this.elementData; 891 if (i >= elementData.length) 892 throw new ConcurrentModificationException(); 893 cursor = i; 894 return (E) elementData[lastRet = i]; 895 } 896 897 public void set(E e) { 898 if (lastRet < 0) 899 throw new IllegalStateException(); 900 checkForComodification(); 901 902 try { 903 ArrayList.this.set(lastRet, e); 904 } catch (IndexOutOfBoundsException ex) { 905 throw new ConcurrentModificationException(); 906 } 907 } 908 909 public void add(E e) { 910 checkForComodification(); 911 912 try { 913 int i = cursor; 914 ArrayList.this.add(i, e); 915 cursor = i + 1; 916 lastRet = -1; 917 expectedModCount = modCount; 918 } catch (IndexOutOfBoundsException ex) { 919 throw new ConcurrentModificationException(); 920 } 921 } 922 } 923 924 /** 925 * Returns a view of the portion of this list between the specified 926 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If 927 * {@code fromIndex} and {@code toIndex} are equal, the returned list is 928 * empty.) The returned list is backed by this list, so non-structural 929 * changes in the returned list are reflected in this list, and vice-versa. 930 * The returned list supports all of the optional list operations. 931 * 932 * <p>This method eliminates the need for explicit range operations (of 933 * the sort that commonly exist for arrays). Any operation that expects 934 * a list can be used as a range operation by passing a subList view 935 * instead of a whole list. For example, the following idiom 936 * removes a range of elements from a list: 937 * <pre> 938 * list.subList(from, to).clear(); 939 * </pre> 940 * Similar idioms may be constructed for {@link #indexOf(Object)} and 941 * {@link #lastIndexOf(Object)}, and all of the algorithms in the 942 * {@link Collections} class can be applied to a subList. 943 * 944 * <p>The semantics of the list returned by this method become undefined if 945 * the backing list (i.e., this list) is <i>structurally modified</i> in 946 * any way other than via the returned list. (Structural modifications are 947 * those that change the size of this list, or otherwise perturb it in such 948 * a fashion that iterations in progress may yield incorrect results.) 949 * 950 * @throws IndexOutOfBoundsException {@inheritDoc} 951 * @throws IllegalArgumentException {@inheritDoc} 952 */ 953 public List<E> subList(int fromIndex, int toIndex) { 954 subListRangeCheck(fromIndex, toIndex, size); 955 return new SubList(this, 0, fromIndex, toIndex); 956 } 957 958 static void subListRangeCheck(int fromIndex, int toIndex, int size) { 959 if (fromIndex < 0) 960 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); 961 if (toIndex > size) 962 throw new IndexOutOfBoundsException("toIndex = " + toIndex); 963 if (fromIndex > toIndex) 964 throw new IllegalArgumentException("fromIndex(" + fromIndex + 965 ") > toIndex(" + toIndex + ")"); 966 } 967 968 private class SubList extends AbstractList<E> implements RandomAccess { 969 private final AbstractList<E> parent; 970 private final int parentOffset; 971 private final int offset; 972 int size; 973 974 SubList(AbstractList<E> parent, 975 int offset, int fromIndex, int toIndex) { 976 this.parent = parent; 977 this.parentOffset = fromIndex; 978 this.offset = offset + fromIndex; 979 this.size = toIndex - fromIndex; 980 this.modCount = ArrayList.this.modCount; 981 } 982 983 public E set(int index, E e) { 984 rangeCheck(index); 985 checkForComodification(); 986 E oldValue = ArrayList.this.elementData(offset + index); 987 ArrayList.this.elementData[offset + index] = e; 988 return oldValue; 989 } 990 991 public E get(int index) { 992 rangeCheck(index); 993 checkForComodification(); 994 return ArrayList.this.elementData(offset + index); 995 } 996 997 public int size() { 998 checkForComodification(); 999 return this.size; 1000 } 1001 1002 public void add(int index, E e) { 1003 rangeCheckForAdd(index); 1004 checkForComodification(); 1005 parent.add(parentOffset + index, e); 1006 this.modCount = parent.modCount; 1007 this.size++; 1008 } 1009 1010 public E remove(int index) { 1011 rangeCheck(index); 1012 checkForComodification(); 1013 E result = parent.remove(parentOffset + index); 1014 this.modCount = parent.modCount; 1015 this.size--; 1016 return result; 1017 } 1018 1019 protected void removeRange(int fromIndex, int toIndex) { 1020 checkForComodification(); 1021 parent.removeRange(parentOffset + fromIndex, 1022 parentOffset + toIndex); 1023 this.modCount = parent.modCount; 1024 this.size -= toIndex - fromIndex; 1025 } 1026 1027 public boolean addAll(Collection<? extends E> c) { 1028 return addAll(this.size, c); 1029 } 1030 1031 public boolean addAll(int index, Collection<? extends E> c) { 1032 rangeCheckForAdd(index); 1033 int cSize = c.size(); 1034 if (cSize==0) 1035 return false; 1036 1037 checkForComodification(); 1038 parent.addAll(parentOffset + index, c); 1039 this.modCount = parent.modCount; 1040 this.size += cSize; 1041 return true; 1042 } 1043 1044 public Iterator<E> iterator() { 1045 return listIterator(); 1046 } 1047 1048 public ListIterator<E> listIterator(final int index) { 1049 checkForComodification(); 1050 rangeCheckForAdd(index); 1051 final int offset = this.offset; 1052 1053 return new ListIterator<E>() { 1054 int cursor = index; 1055 int lastRet = -1; 1056 int expectedModCount = ArrayList.this.modCount; 1057 1058 public boolean hasNext() { 1059 return cursor != SubList.this.size; 1060 } 1061 1062 @SuppressWarnings("unchecked") 1063 public E next() { 1064 checkForComodification(); 1065 int i = cursor; 1066 if (i >= SubList.this.size) 1067 throw new NoSuchElementException(); 1068 Object[] elementData = ArrayList.this.elementData; 1069 if (offset + i >= elementData.length) 1070 throw new ConcurrentModificationException(); 1071 cursor = i + 1; 1072 return (E) elementData[offset + (lastRet = i)]; 1073 } 1074 1075 public boolean hasPrevious() { 1076 return cursor != 0; 1077 } 1078 1079 @SuppressWarnings("unchecked") 1080 public E previous() { 1081 checkForComodification(); 1082 int i = cursor - 1; 1083 if (i < 0) 1084 throw new NoSuchElementException(); 1085 Object[] elementData = ArrayList.this.elementData; 1086 if (offset + i >= elementData.length) 1087 throw new ConcurrentModificationException(); 1088 cursor = i; 1089 return (E) elementData[offset + (lastRet = i)]; 1090 } 1091 1092 public int nextIndex() { 1093 return cursor; 1094 } 1095 1096 public int previousIndex() { 1097 return cursor - 1; 1098 } 1099 1100 public void remove() { 1101 if (lastRet < 0) 1102 throw new IllegalStateException(); 1103 checkForComodification(); 1104 1105 try { 1106 SubList.this.remove(lastRet); 1107 cursor = lastRet; 1108 lastRet = -1; 1109 expectedModCount = ArrayList.this.modCount; 1110 } catch (IndexOutOfBoundsException ex) { 1111 throw new ConcurrentModificationException(); 1112 } 1113 } 1114 1115 public void set(E e) { 1116 if (lastRet < 0) 1117 throw new IllegalStateException(); 1118 checkForComodification(); 1119 1120 try { 1121 ArrayList.this.set(offset + lastRet, e); 1122 } catch (IndexOutOfBoundsException ex) { 1123 throw new ConcurrentModificationException(); 1124 } 1125 } 1126 1127 public void add(E e) { 1128 checkForComodification(); 1129 1130 try { 1131 int i = cursor; 1132 SubList.this.add(i, e); 1133 cursor = i + 1; 1134 lastRet = -1; 1135 expectedModCount = ArrayList.this.modCount; 1136 } catch (IndexOutOfBoundsException ex) { 1137 throw new ConcurrentModificationException(); 1138 } 1139 } 1140 1141 final void checkForComodification() { 1142 if (expectedModCount != ArrayList.this.modCount) 1143 throw new ConcurrentModificationException(); 1144 } 1145 }; 1146 } 1147 1148 public List<E> subList(int fromIndex, int toIndex) { 1149 subListRangeCheck(fromIndex, toIndex, size); 1150 return new SubList(this, offset, fromIndex, toIndex); 1151 } 1152 1153 private void rangeCheck(int index) { 1154 if (index < 0 || index >= this.size) 1155 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 1156 } 1157 1158 private void rangeCheckForAdd(int index) { 1159 if (index < 0 || index > this.size) 1160 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 1161 } 1162 1163 private String outOfBoundsMsg(int index) { 1164 return "Index: "+index+", Size: "+this.size; 1165 } 1166 1167 private void checkForComodification() { 1168 if (ArrayList.this.modCount != this.modCount) 1169 throw new ConcurrentModificationException(); 1170 } 1171 } 1172} 1173