ArrayList.java revision a68b1a5ba82ef8cc19aafdce7d9c7f9631943f84
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 // Android-changed : Throw an IOOBE if toIndex < fromIndex as documented. 615 // All the other cases (negative indices, or indices greater than the size 616 // will be thrown by System#arrayCopy. 617 if (toIndex < fromIndex) { 618 throw new IndexOutOfBoundsException("toIndex < fromIndex"); 619 } 620 621 modCount++; 622 int numMoved = size - toIndex; 623 System.arraycopy(elementData, toIndex, elementData, fromIndex, 624 numMoved); 625 626 // clear to let GC do its work 627 int newSize = size - (toIndex-fromIndex); 628 for (int i = newSize; i < size; i++) { 629 elementData[i] = null; 630 } 631 size = newSize; 632 } 633 634 /** 635 * Checks if the given index is in range. If not, throws an appropriate 636 * runtime exception. This method does *not* check if the index is 637 * negative: It is always used immediately prior to an array access, 638 * which throws an ArrayIndexOutOfBoundsException if index is negative. 639 */ 640 private void rangeCheck(int index) { 641 if (index >= size) 642 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 643 } 644 645 /** 646 * A version of rangeCheck used by add and addAll. 647 */ 648 private void rangeCheckForAdd(int index) { 649 if (index > size || index < 0) 650 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 651 } 652 653 /** 654 * Constructs an IndexOutOfBoundsException detail message. 655 * Of the many possible refactorings of the error handling code, 656 * this "outlining" performs best with both server and client VMs. 657 */ 658 private String outOfBoundsMsg(int index) { 659 return "Index: "+index+", Size: "+size; 660 } 661 662 /** 663 * Removes from this list all of its elements that are contained in the 664 * specified collection. 665 * 666 * @param c collection containing elements to be removed from this list 667 * @return {@code true} if this list changed as a result of the call 668 * @throws ClassCastException if the class of an element of this list 669 * is incompatible with the specified collection 670 * (<a href="Collection.html#optional-restrictions">optional</a>) 671 * @throws NullPointerException if this list contains a null element and the 672 * specified collection does not permit null elements 673 * (<a href="Collection.html#optional-restrictions">optional</a>), 674 * or if the specified collection is null 675 * @see Collection#contains(Object) 676 */ 677 public boolean removeAll(Collection<?> c) { 678 return batchRemove(c, false); 679 } 680 681 /** 682 * Retains only the elements in this list that are contained in the 683 * specified collection. In other words, removes from this list all 684 * of its elements that are not contained in the specified collection. 685 * 686 * @param c collection containing elements to be retained in this list 687 * @return {@code true} if this list changed as a result of the call 688 * @throws ClassCastException if the class of an element of this list 689 * is incompatible with the specified collection 690 * (<a href="Collection.html#optional-restrictions">optional</a>) 691 * @throws NullPointerException if this list contains a null element and the 692 * specified collection does not permit null elements 693 * (<a href="Collection.html#optional-restrictions">optional</a>), 694 * or if the specified collection is null 695 * @see Collection#contains(Object) 696 */ 697 public boolean retainAll(Collection<?> c) { 698 return batchRemove(c, true); 699 } 700 701 private boolean batchRemove(Collection<?> c, boolean complement) { 702 final Object[] elementData = this.elementData; 703 int r = 0, w = 0; 704 boolean modified = false; 705 try { 706 for (; r < size; r++) 707 if (c.contains(elementData[r]) == complement) 708 elementData[w++] = elementData[r]; 709 } finally { 710 // Preserve behavioral compatibility with AbstractCollection, 711 // even if c.contains() throws. 712 if (r != size) { 713 System.arraycopy(elementData, r, 714 elementData, w, 715 size - r); 716 w += size - r; 717 } 718 if (w != size) { 719 // clear to let GC do its work 720 for (int i = w; i < size; i++) 721 elementData[i] = null; 722 modCount += size - w; 723 size = w; 724 modified = true; 725 } 726 } 727 return modified; 728 } 729 730 /** 731 * Save the state of the <tt>ArrayList</tt> instance to a stream (that 732 * is, serialize it). 733 * 734 * @serialData The length of the array backing the <tt>ArrayList</tt> 735 * instance is emitted (int), followed by all of its elements 736 * (each an <tt>Object</tt>) in the proper order. 737 */ 738 private void writeObject(java.io.ObjectOutputStream s) 739 throws java.io.IOException{ 740 // Write out element count, and any hidden stuff 741 int expectedModCount = modCount; 742 s.defaultWriteObject(); 743 744 // Write out size as capacity for behavioural compatibility with clone() 745 s.writeInt(size); 746 747 // Write out all elements in the proper order. 748 for (int i=0; i<size; i++) { 749 s.writeObject(elementData[i]); 750 } 751 752 if (modCount != expectedModCount) { 753 throw new ConcurrentModificationException(); 754 } 755 } 756 757 /** 758 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, 759 * deserialize it). 760 */ 761 private void readObject(java.io.ObjectInputStream s) 762 throws java.io.IOException, ClassNotFoundException { 763 elementData = EMPTY_ELEMENTDATA; 764 765 // Read in size, and any hidden stuff 766 s.defaultReadObject(); 767 768 // Read in capacity 769 s.readInt(); // ignored 770 771 if (size > 0) { 772 // be like clone(), allocate array based upon size not capacity 773 ensureCapacityInternal(size); 774 775 Object[] a = elementData; 776 // Read in all elements in the proper order. 777 for (int i=0; i<size; i++) { 778 a[i] = s.readObject(); 779 } 780 } 781 } 782 783 /** 784 * Returns a list iterator over the elements in this list (in proper 785 * sequence), starting at the specified position in the list. 786 * The specified index indicates the first element that would be 787 * returned by an initial call to {@link ListIterator#next next}. 788 * An initial call to {@link ListIterator#previous previous} would 789 * return the element with the specified index minus one. 790 * 791 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 792 * 793 * @throws IndexOutOfBoundsException {@inheritDoc} 794 */ 795 public ListIterator<E> listIterator(int index) { 796 if (index < 0 || index > size) 797 throw new IndexOutOfBoundsException("Index: "+index); 798 return new ListItr(index); 799 } 800 801 /** 802 * Returns a list iterator over the elements in this list (in proper 803 * sequence). 804 * 805 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 806 * 807 * @see #listIterator(int) 808 */ 809 public ListIterator<E> listIterator() { 810 return new ListItr(0); 811 } 812 813 /** 814 * Returns an iterator over the elements in this list in proper sequence. 815 * 816 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 817 * 818 * @return an iterator over the elements in this list in proper sequence 819 */ 820 public Iterator<E> iterator() { 821 return new Itr(); 822 } 823 824 /** 825 * An optimized version of AbstractList.Itr 826 */ 827 private class Itr implements Iterator<E> { 828 int cursor; // index of next element to return 829 int lastRet = -1; // index of last element returned; -1 if no such 830 int expectedModCount = modCount; 831 832 public boolean hasNext() { 833 return cursor != size; 834 } 835 836 @SuppressWarnings("unchecked") 837 public E next() { 838 checkForComodification(); 839 int i = cursor; 840 if (i >= size) 841 throw new NoSuchElementException(); 842 Object[] elementData = ArrayList.this.elementData; 843 if (i >= elementData.length) 844 throw new ConcurrentModificationException(); 845 cursor = i + 1; 846 return (E) elementData[lastRet = i]; 847 } 848 849 public void remove() { 850 if (lastRet < 0) 851 throw new IllegalStateException(); 852 checkForComodification(); 853 854 try { 855 ArrayList.this.remove(lastRet); 856 cursor = lastRet; 857 lastRet = -1; 858 expectedModCount = modCount; 859 } catch (IndexOutOfBoundsException ex) { 860 throw new ConcurrentModificationException(); 861 } 862 } 863 864 final void checkForComodification() { 865 if (modCount != expectedModCount) 866 throw new ConcurrentModificationException(); 867 } 868 } 869 870 /** 871 * An optimized version of AbstractList.ListItr 872 */ 873 private class ListItr extends Itr implements ListIterator<E> { 874 ListItr(int index) { 875 super(); 876 cursor = index; 877 } 878 879 public boolean hasPrevious() { 880 return cursor != 0; 881 } 882 883 public int nextIndex() { 884 return cursor; 885 } 886 887 public int previousIndex() { 888 return cursor - 1; 889 } 890 891 @SuppressWarnings("unchecked") 892 public E previous() { 893 checkForComodification(); 894 int i = cursor - 1; 895 if (i < 0) 896 throw new NoSuchElementException(); 897 Object[] elementData = ArrayList.this.elementData; 898 if (i >= elementData.length) 899 throw new ConcurrentModificationException(); 900 cursor = i; 901 return (E) elementData[lastRet = i]; 902 } 903 904 public void set(E e) { 905 if (lastRet < 0) 906 throw new IllegalStateException(); 907 checkForComodification(); 908 909 try { 910 ArrayList.this.set(lastRet, e); 911 } catch (IndexOutOfBoundsException ex) { 912 throw new ConcurrentModificationException(); 913 } 914 } 915 916 public void add(E e) { 917 checkForComodification(); 918 919 try { 920 int i = cursor; 921 ArrayList.this.add(i, e); 922 cursor = i + 1; 923 lastRet = -1; 924 expectedModCount = modCount; 925 } catch (IndexOutOfBoundsException ex) { 926 throw new ConcurrentModificationException(); 927 } 928 } 929 } 930 931 /** 932 * Returns a view of the portion of this list between the specified 933 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If 934 * {@code fromIndex} and {@code toIndex} are equal, the returned list is 935 * empty.) The returned list is backed by this list, so non-structural 936 * changes in the returned list are reflected in this list, and vice-versa. 937 * The returned list supports all of the optional list operations. 938 * 939 * <p>This method eliminates the need for explicit range operations (of 940 * the sort that commonly exist for arrays). Any operation that expects 941 * a list can be used as a range operation by passing a subList view 942 * instead of a whole list. For example, the following idiom 943 * removes a range of elements from a list: 944 * <pre> 945 * list.subList(from, to).clear(); 946 * </pre> 947 * Similar idioms may be constructed for {@link #indexOf(Object)} and 948 * {@link #lastIndexOf(Object)}, and all of the algorithms in the 949 * {@link Collections} class can be applied to a subList. 950 * 951 * <p>The semantics of the list returned by this method become undefined if 952 * the backing list (i.e., this list) is <i>structurally modified</i> in 953 * any way other than via the returned list. (Structural modifications are 954 * those that change the size of this list, or otherwise perturb it in such 955 * a fashion that iterations in progress may yield incorrect results.) 956 * 957 * @throws IndexOutOfBoundsException {@inheritDoc} 958 * @throws IllegalArgumentException {@inheritDoc} 959 */ 960 public List<E> subList(int fromIndex, int toIndex) { 961 subListRangeCheck(fromIndex, toIndex, size); 962 return new SubList(this, 0, fromIndex, toIndex); 963 } 964 965 static void subListRangeCheck(int fromIndex, int toIndex, int size) { 966 if (fromIndex < 0) 967 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); 968 if (toIndex > size) 969 throw new IndexOutOfBoundsException("toIndex = " + toIndex); 970 if (fromIndex > toIndex) 971 throw new IllegalArgumentException("fromIndex(" + fromIndex + 972 ") > toIndex(" + toIndex + ")"); 973 } 974 975 private class SubList extends AbstractList<E> implements RandomAccess { 976 private final AbstractList<E> parent; 977 private final int parentOffset; 978 private final int offset; 979 int size; 980 981 SubList(AbstractList<E> parent, 982 int offset, int fromIndex, int toIndex) { 983 this.parent = parent; 984 this.parentOffset = fromIndex; 985 this.offset = offset + fromIndex; 986 this.size = toIndex - fromIndex; 987 this.modCount = ArrayList.this.modCount; 988 } 989 990 public E set(int index, E e) { 991 rangeCheck(index); 992 checkForComodification(); 993 E oldValue = ArrayList.this.elementData(offset + index); 994 ArrayList.this.elementData[offset + index] = e; 995 return oldValue; 996 } 997 998 public E get(int index) { 999 rangeCheck(index); 1000 checkForComodification(); 1001 return ArrayList.this.elementData(offset + index); 1002 } 1003 1004 public int size() { 1005 checkForComodification(); 1006 return this.size; 1007 } 1008 1009 public void add(int index, E e) { 1010 rangeCheckForAdd(index); 1011 checkForComodification(); 1012 parent.add(parentOffset + index, e); 1013 this.modCount = parent.modCount; 1014 this.size++; 1015 } 1016 1017 public E remove(int index) { 1018 rangeCheck(index); 1019 checkForComodification(); 1020 E result = parent.remove(parentOffset + index); 1021 this.modCount = parent.modCount; 1022 this.size--; 1023 return result; 1024 } 1025 1026 protected void removeRange(int fromIndex, int toIndex) { 1027 checkForComodification(); 1028 parent.removeRange(parentOffset + fromIndex, 1029 parentOffset + toIndex); 1030 this.modCount = parent.modCount; 1031 this.size -= toIndex - fromIndex; 1032 } 1033 1034 public boolean addAll(Collection<? extends E> c) { 1035 return addAll(this.size, c); 1036 } 1037 1038 public boolean addAll(int index, Collection<? extends E> c) { 1039 rangeCheckForAdd(index); 1040 int cSize = c.size(); 1041 if (cSize==0) 1042 return false; 1043 1044 checkForComodification(); 1045 parent.addAll(parentOffset + index, c); 1046 this.modCount = parent.modCount; 1047 this.size += cSize; 1048 return true; 1049 } 1050 1051 public Iterator<E> iterator() { 1052 return listIterator(); 1053 } 1054 1055 public ListIterator<E> listIterator(final int index) { 1056 checkForComodification(); 1057 rangeCheckForAdd(index); 1058 final int offset = this.offset; 1059 1060 return new ListIterator<E>() { 1061 int cursor = index; 1062 int lastRet = -1; 1063 int expectedModCount = ArrayList.this.modCount; 1064 1065 public boolean hasNext() { 1066 return cursor != SubList.this.size; 1067 } 1068 1069 @SuppressWarnings("unchecked") 1070 public E next() { 1071 checkForComodification(); 1072 int i = cursor; 1073 if (i >= SubList.this.size) 1074 throw new NoSuchElementException(); 1075 Object[] elementData = ArrayList.this.elementData; 1076 if (offset + i >= elementData.length) 1077 throw new ConcurrentModificationException(); 1078 cursor = i + 1; 1079 return (E) elementData[offset + (lastRet = i)]; 1080 } 1081 1082 public boolean hasPrevious() { 1083 return cursor != 0; 1084 } 1085 1086 @SuppressWarnings("unchecked") 1087 public E previous() { 1088 checkForComodification(); 1089 int i = cursor - 1; 1090 if (i < 0) 1091 throw new NoSuchElementException(); 1092 Object[] elementData = ArrayList.this.elementData; 1093 if (offset + i >= elementData.length) 1094 throw new ConcurrentModificationException(); 1095 cursor = i; 1096 return (E) elementData[offset + (lastRet = i)]; 1097 } 1098 1099 public int nextIndex() { 1100 return cursor; 1101 } 1102 1103 public int previousIndex() { 1104 return cursor - 1; 1105 } 1106 1107 public void remove() { 1108 if (lastRet < 0) 1109 throw new IllegalStateException(); 1110 checkForComodification(); 1111 1112 try { 1113 SubList.this.remove(lastRet); 1114 cursor = lastRet; 1115 lastRet = -1; 1116 expectedModCount = ArrayList.this.modCount; 1117 } catch (IndexOutOfBoundsException ex) { 1118 throw new ConcurrentModificationException(); 1119 } 1120 } 1121 1122 public void set(E e) { 1123 if (lastRet < 0) 1124 throw new IllegalStateException(); 1125 checkForComodification(); 1126 1127 try { 1128 ArrayList.this.set(offset + lastRet, e); 1129 } catch (IndexOutOfBoundsException ex) { 1130 throw new ConcurrentModificationException(); 1131 } 1132 } 1133 1134 public void add(E e) { 1135 checkForComodification(); 1136 1137 try { 1138 int i = cursor; 1139 SubList.this.add(i, e); 1140 cursor = i + 1; 1141 lastRet = -1; 1142 expectedModCount = ArrayList.this.modCount; 1143 } catch (IndexOutOfBoundsException ex) { 1144 throw new ConcurrentModificationException(); 1145 } 1146 } 1147 1148 final void checkForComodification() { 1149 if (expectedModCount != ArrayList.this.modCount) 1150 throw new ConcurrentModificationException(); 1151 } 1152 }; 1153 } 1154 1155 public List<E> subList(int fromIndex, int toIndex) { 1156 subListRangeCheck(fromIndex, toIndex, size); 1157 return new SubList(this, offset, fromIndex, toIndex); 1158 } 1159 1160 private void rangeCheck(int index) { 1161 if (index < 0 || index >= this.size) 1162 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 1163 } 1164 1165 private void rangeCheckForAdd(int index) { 1166 if (index < 0 || index > this.size) 1167 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 1168 } 1169 1170 private String outOfBoundsMsg(int index) { 1171 return "Index: "+index+", Size: "+this.size; 1172 } 1173 1174 private void checkForComodification() { 1175 if (ArrayList.this.modCount != this.modCount) 1176 throw new ConcurrentModificationException(); 1177 } 1178 } 1179} 1180