ArrayList.java revision 3be987f0f18648b3c532c8b89d09505e18594241
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 /** 397 * Returns the element at the specified position in this list. 398 * 399 * @param index index of the element to return 400 * @return the element at the specified position in this list 401 * @throws IndexOutOfBoundsException {@inheritDoc} 402 */ 403 public E get(int index) { 404 if (index >= size) 405 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 406 407 return (E) elementData[index]; 408 } 409 410 /** 411 * Replaces the element at the specified position in this list with 412 * the specified element. 413 * 414 * @param index index of the element to replace 415 * @param element element to be stored at the specified position 416 * @return the element previously at the specified position 417 * @throws IndexOutOfBoundsException {@inheritDoc} 418 */ 419 public E set(int index, E element) { 420 if (index >= size) 421 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 422 423 E oldValue = (E) elementData[index]; 424 elementData[index] = element; 425 return oldValue; 426 } 427 428 /** 429 * Appends the specified element to the end of this list. 430 * 431 * @param e element to be appended to this list 432 * @return <tt>true</tt> (as specified by {@link Collection#add}) 433 */ 434 public boolean add(E e) { 435 ensureCapacityInternal(size + 1); // Increments modCount!! 436 elementData[size++] = e; 437 return true; 438 } 439 440 /** 441 * Inserts the specified element at the specified position in this 442 * list. Shifts the element currently at that position (if any) and 443 * any subsequent elements to the right (adds one to their indices). 444 * 445 * @param index index at which the specified element is to be inserted 446 * @param element element to be inserted 447 * @throws IndexOutOfBoundsException {@inheritDoc} 448 */ 449 public void add(int index, E element) { 450 if (index > size || index < 0) 451 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 452 453 ensureCapacityInternal(size + 1); // Increments modCount!! 454 System.arraycopy(elementData, index, elementData, index + 1, 455 size - index); 456 elementData[index] = element; 457 size++; 458 } 459 460 /** 461 * Removes the element at the specified position in this list. 462 * Shifts any subsequent elements to the left (subtracts one from their 463 * indices). 464 * 465 * @param index the index of the element to be removed 466 * @return the element that was removed from the list 467 * @throws IndexOutOfBoundsException {@inheritDoc} 468 */ 469 public E remove(int index) { 470 if (index >= size) 471 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 472 473 modCount++; 474 E oldValue = (E) elementData[index]; 475 476 int numMoved = size - index - 1; 477 if (numMoved > 0) 478 System.arraycopy(elementData, index+1, elementData, index, 479 numMoved); 480 elementData[--size] = null; // clear to let GC do its work 481 482 return oldValue; 483 } 484 485 /** 486 * Removes the first occurrence of the specified element from this list, 487 * if it is present. If the list does not contain the element, it is 488 * unchanged. More formally, removes the element with the lowest index 489 * <tt>i</tt> such that 490 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> 491 * (if such an element exists). Returns <tt>true</tt> if this list 492 * contained the specified element (or equivalently, if this list 493 * changed as a result of the call). 494 * 495 * @param o element to be removed from this list, if present 496 * @return <tt>true</tt> if this list contained the specified element 497 */ 498 public boolean remove(Object o) { 499 if (o == null) { 500 for (int index = 0; index < size; index++) 501 if (elementData[index] == null) { 502 fastRemove(index); 503 return true; 504 } 505 } else { 506 for (int index = 0; index < size; index++) 507 if (o.equals(elementData[index])) { 508 fastRemove(index); 509 return true; 510 } 511 } 512 return false; 513 } 514 515 /* 516 * Private remove method that skips bounds checking and does not 517 * return the value removed. 518 */ 519 private void fastRemove(int index) { 520 modCount++; 521 int numMoved = size - index - 1; 522 if (numMoved > 0) 523 System.arraycopy(elementData, index+1, elementData, index, 524 numMoved); 525 elementData[--size] = null; // clear to let GC do its work 526 } 527 528 /** 529 * Removes all of the elements from this list. The list will 530 * be empty after this call returns. 531 */ 532 public void clear() { 533 modCount++; 534 535 // clear to let GC do its work 536 for (int i = 0; i < size; i++) 537 elementData[i] = null; 538 539 size = 0; 540 } 541 542 /** 543 * Appends all of the elements in the specified collection to the end of 544 * this list, in the order that they are returned by the 545 * specified collection's Iterator. The behavior of this operation is 546 * undefined if the specified collection is modified while the operation 547 * is in progress. (This implies that the behavior of this call is 548 * undefined if the specified collection is this list, and this 549 * list is nonempty.) 550 * 551 * @param c collection containing elements to be added to this list 552 * @return <tt>true</tt> if this list changed as a result of the call 553 * @throws NullPointerException if the specified collection is null 554 */ 555 public boolean addAll(Collection<? extends E> c) { 556 Object[] a = c.toArray(); 557 int numNew = a.length; 558 ensureCapacityInternal(size + numNew); // Increments modCount 559 System.arraycopy(a, 0, elementData, size, numNew); 560 size += numNew; 561 return numNew != 0; 562 } 563 564 /** 565 * Inserts all of the elements in the specified collection into this 566 * list, starting at the specified position. Shifts the element 567 * currently at that position (if any) and any subsequent elements to 568 * the right (increases their indices). The new elements will appear 569 * in the list in the order that they are returned by the 570 * specified collection's iterator. 571 * 572 * @param index index at which to insert the first element from the 573 * specified collection 574 * @param c collection containing elements to be added to this list 575 * @return <tt>true</tt> if this list changed as a result of the call 576 * @throws IndexOutOfBoundsException {@inheritDoc} 577 * @throws NullPointerException if the specified collection is null 578 */ 579 public boolean addAll(int index, Collection<? extends E> c) { 580 if (index > size || index < 0) 581 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 582 583 Object[] a = c.toArray(); 584 int numNew = a.length; 585 ensureCapacityInternal(size + numNew); // Increments modCount 586 587 int numMoved = size - index; 588 if (numMoved > 0) 589 System.arraycopy(elementData, index, elementData, index + numNew, 590 numMoved); 591 592 System.arraycopy(a, 0, elementData, index, numNew); 593 size += numNew; 594 return numNew != 0; 595 } 596 597 /** 598 * Removes from this list all of the elements whose index is between 599 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. 600 * Shifts any succeeding elements to the left (reduces their index). 601 * This call shortens the list by {@code (toIndex - fromIndex)} elements. 602 * (If {@code toIndex==fromIndex}, this operation has no effect.) 603 * 604 * @throws IndexOutOfBoundsException if {@code fromIndex} or 605 * {@code toIndex} is out of range 606 * ({@code fromIndex < 0 || 607 * fromIndex >= size() || 608 * toIndex > size() || 609 * toIndex < fromIndex}) 610 */ 611 protected void removeRange(int fromIndex, int toIndex) { 612 // Android-changed : Throw an IOOBE if toIndex < fromIndex as documented. 613 // All the other cases (negative indices, or indices greater than the size 614 // will be thrown by System#arrayCopy. 615 if (toIndex < fromIndex) { 616 throw new IndexOutOfBoundsException("toIndex < fromIndex"); 617 } 618 619 modCount++; 620 int numMoved = size - toIndex; 621 System.arraycopy(elementData, toIndex, elementData, fromIndex, 622 numMoved); 623 624 // clear to let GC do its work 625 int newSize = size - (toIndex-fromIndex); 626 for (int i = newSize; i < size; i++) { 627 elementData[i] = null; 628 } 629 size = newSize; 630 } 631 632 /** 633 * Constructs an IndexOutOfBoundsException detail message. 634 * Of the many possible refactorings of the error handling code, 635 * this "outlining" performs best with both server and client VMs. 636 */ 637 private String outOfBoundsMsg(int index) { 638 return "Index: "+index+", Size: "+size; 639 } 640 641 /** 642 * Removes from this list all of its elements that are contained in the 643 * specified collection. 644 * 645 * @param c collection containing elements to be removed from this list 646 * @return {@code true} if this list changed as a result of the call 647 * @throws ClassCastException if the class of an element of this list 648 * is incompatible with the specified collection 649 * (<a href="Collection.html#optional-restrictions">optional</a>) 650 * @throws NullPointerException if this list contains a null element and the 651 * specified collection does not permit null elements 652 * (<a href="Collection.html#optional-restrictions">optional</a>), 653 * or if the specified collection is null 654 * @see Collection#contains(Object) 655 */ 656 public boolean removeAll(Collection<?> c) { 657 return batchRemove(c, false); 658 } 659 660 /** 661 * Retains only the elements in this list that are contained in the 662 * specified collection. In other words, removes from this list all 663 * of its elements that are not contained in the specified collection. 664 * 665 * @param c collection containing elements to be retained in this list 666 * @return {@code true} if this list changed as a result of the call 667 * @throws ClassCastException if the class of an element of this list 668 * is incompatible with the specified collection 669 * (<a href="Collection.html#optional-restrictions">optional</a>) 670 * @throws NullPointerException if this list contains a null element and the 671 * specified collection does not permit null elements 672 * (<a href="Collection.html#optional-restrictions">optional</a>), 673 * or if the specified collection is null 674 * @see Collection#contains(Object) 675 */ 676 public boolean retainAll(Collection<?> c) { 677 return batchRemove(c, true); 678 } 679 680 private boolean batchRemove(Collection<?> c, boolean complement) { 681 final Object[] elementData = this.elementData; 682 int r = 0, w = 0; 683 boolean modified = false; 684 try { 685 for (; r < size; r++) 686 if (c.contains(elementData[r]) == complement) 687 elementData[w++] = elementData[r]; 688 } finally { 689 // Preserve behavioral compatibility with AbstractCollection, 690 // even if c.contains() throws. 691 if (r != size) { 692 System.arraycopy(elementData, r, 693 elementData, w, 694 size - r); 695 w += size - r; 696 } 697 if (w != size) { 698 // clear to let GC do its work 699 for (int i = w; i < size; i++) 700 elementData[i] = null; 701 modCount += size - w; 702 size = w; 703 modified = true; 704 } 705 } 706 return modified; 707 } 708 709 /** 710 * Save the state of the <tt>ArrayList</tt> instance to a stream (that 711 * is, serialize it). 712 * 713 * @serialData The length of the array backing the <tt>ArrayList</tt> 714 * instance is emitted (int), followed by all of its elements 715 * (each an <tt>Object</tt>) in the proper order. 716 */ 717 private void writeObject(java.io.ObjectOutputStream s) 718 throws java.io.IOException{ 719 // Write out element count, and any hidden stuff 720 int expectedModCount = modCount; 721 s.defaultWriteObject(); 722 723 // Write out size as capacity for behavioural compatibility with clone() 724 s.writeInt(size); 725 726 // Write out all elements in the proper order. 727 for (int i=0; i<size; i++) { 728 s.writeObject(elementData[i]); 729 } 730 731 if (modCount != expectedModCount) { 732 throw new ConcurrentModificationException(); 733 } 734 } 735 736 /** 737 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, 738 * deserialize it). 739 */ 740 private void readObject(java.io.ObjectInputStream s) 741 throws java.io.IOException, ClassNotFoundException { 742 elementData = EMPTY_ELEMENTDATA; 743 744 // Read in size, and any hidden stuff 745 s.defaultReadObject(); 746 747 // Read in capacity 748 s.readInt(); // ignored 749 750 if (size > 0) { 751 // be like clone(), allocate array based upon size not capacity 752 ensureCapacityInternal(size); 753 754 Object[] a = elementData; 755 // Read in all elements in the proper order. 756 for (int i=0; i<size; i++) { 757 a[i] = s.readObject(); 758 } 759 } 760 } 761 762 /** 763 * Returns a list iterator over the elements in this list (in proper 764 * sequence), starting at the specified position in the list. 765 * The specified index indicates the first element that would be 766 * returned by an initial call to {@link ListIterator#next next}. 767 * An initial call to {@link ListIterator#previous previous} would 768 * return the element with the specified index minus one. 769 * 770 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 771 * 772 * @throws IndexOutOfBoundsException {@inheritDoc} 773 */ 774 public ListIterator<E> listIterator(int index) { 775 if (index < 0 || index > size) 776 throw new IndexOutOfBoundsException("Index: "+index); 777 return new ListItr(index); 778 } 779 780 /** 781 * Returns a list iterator over the elements in this list (in proper 782 * sequence). 783 * 784 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 785 * 786 * @see #listIterator(int) 787 */ 788 public ListIterator<E> listIterator() { 789 return new ListItr(0); 790 } 791 792 /** 793 * Returns an iterator over the elements in this list in proper sequence. 794 * 795 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 796 * 797 * @return an iterator over the elements in this list in proper sequence 798 */ 799 public Iterator<E> iterator() { 800 return new Itr(); 801 } 802 803 /** 804 * An optimized version of AbstractList.Itr 805 */ 806 private class Itr implements Iterator<E> { 807 int cursor; // index of next element to return 808 int lastRet = -1; // index of last element returned; -1 if no such 809 int expectedModCount = modCount; 810 811 public boolean hasNext() { 812 return cursor != size; 813 } 814 815 @SuppressWarnings("unchecked") 816 public E next() { 817 if (modCount != expectedModCount) 818 throw new ConcurrentModificationException(); 819 int i = cursor; 820 if (i >= size) 821 throw new NoSuchElementException(); 822 Object[] elementData = ArrayList.this.elementData; 823 if (i >= elementData.length) 824 throw new ConcurrentModificationException(); 825 cursor = i + 1; 826 return (E) elementData[lastRet = i]; 827 } 828 829 public void remove() { 830 if (lastRet < 0) 831 throw new IllegalStateException(); 832 if (modCount != expectedModCount) 833 throw new ConcurrentModificationException(); 834 835 try { 836 ArrayList.this.remove(lastRet); 837 cursor = lastRet; 838 lastRet = -1; 839 expectedModCount = modCount; 840 } catch (IndexOutOfBoundsException ex) { 841 throw new ConcurrentModificationException(); 842 } 843 } 844 } 845 846 /** 847 * An optimized version of AbstractList.ListItr 848 */ 849 private class ListItr extends Itr implements ListIterator<E> { 850 ListItr(int index) { 851 super(); 852 cursor = index; 853 } 854 855 public boolean hasPrevious() { 856 return cursor != 0; 857 } 858 859 public int nextIndex() { 860 return cursor; 861 } 862 863 public int previousIndex() { 864 return cursor - 1; 865 } 866 867 @SuppressWarnings("unchecked") 868 public E previous() { 869 if (modCount != expectedModCount) 870 throw new ConcurrentModificationException(); 871 int i = cursor - 1; 872 if (i < 0) 873 throw new NoSuchElementException(); 874 Object[] elementData = ArrayList.this.elementData; 875 if (i >= elementData.length) 876 throw new ConcurrentModificationException(); 877 cursor = i; 878 return (E) elementData[lastRet = i]; 879 } 880 881 public void set(E e) { 882 if (lastRet < 0) 883 throw new IllegalStateException(); 884 if (modCount != expectedModCount) 885 throw new ConcurrentModificationException(); 886 887 try { 888 ArrayList.this.set(lastRet, e); 889 } catch (IndexOutOfBoundsException ex) { 890 throw new ConcurrentModificationException(); 891 } 892 } 893 894 public void add(E e) { 895 if (modCount != expectedModCount) 896 throw new ConcurrentModificationException(); 897 898 try { 899 int i = cursor; 900 ArrayList.this.add(i, e); 901 cursor = i + 1; 902 lastRet = -1; 903 expectedModCount = modCount; 904 } catch (IndexOutOfBoundsException ex) { 905 throw new ConcurrentModificationException(); 906 } 907 } 908 } 909 910 /** 911 * Returns a view of the portion of this list between the specified 912 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If 913 * {@code fromIndex} and {@code toIndex} are equal, the returned list is 914 * empty.) The returned list is backed by this list, so non-structural 915 * changes in the returned list are reflected in this list, and vice-versa. 916 * The returned list supports all of the optional list operations. 917 * 918 * <p>This method eliminates the need for explicit range operations (of 919 * the sort that commonly exist for arrays). Any operation that expects 920 * a list can be used as a range operation by passing a subList view 921 * instead of a whole list. For example, the following idiom 922 * removes a range of elements from a list: 923 * <pre> 924 * list.subList(from, to).clear(); 925 * </pre> 926 * Similar idioms may be constructed for {@link #indexOf(Object)} and 927 * {@link #lastIndexOf(Object)}, and all of the algorithms in the 928 * {@link Collections} class can be applied to a subList. 929 * 930 * <p>The semantics of the list returned by this method become undefined if 931 * the backing list (i.e., this list) is <i>structurally modified</i> in 932 * any way other than via the returned list. (Structural modifications are 933 * those that change the size of this list, or otherwise perturb it in such 934 * a fashion that iterations in progress may yield incorrect results.) 935 * 936 * @throws IndexOutOfBoundsException {@inheritDoc} 937 * @throws IllegalArgumentException {@inheritDoc} 938 */ 939 public List<E> subList(int fromIndex, int toIndex) { 940 subListRangeCheck(fromIndex, toIndex, size); 941 return new SubList(this, 0, fromIndex, toIndex); 942 } 943 944 static void subListRangeCheck(int fromIndex, int toIndex, int size) { 945 if (fromIndex < 0) 946 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); 947 if (toIndex > size) 948 throw new IndexOutOfBoundsException("toIndex = " + toIndex); 949 if (fromIndex > toIndex) 950 throw new IllegalArgumentException("fromIndex(" + fromIndex + 951 ") > toIndex(" + toIndex + ")"); 952 } 953 954 private class SubList extends AbstractList<E> implements RandomAccess { 955 private final AbstractList<E> parent; 956 private final int parentOffset; 957 private final int offset; 958 int size; 959 960 SubList(AbstractList<E> parent, 961 int offset, int fromIndex, int toIndex) { 962 this.parent = parent; 963 this.parentOffset = fromIndex; 964 this.offset = offset + fromIndex; 965 this.size = toIndex - fromIndex; 966 this.modCount = ArrayList.this.modCount; 967 } 968 969 public E set(int index, E e) { 970 if (index < 0 || index >= this.size) 971 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 972 if (ArrayList.this.modCount != this.modCount) 973 throw new ConcurrentModificationException(); 974 E oldValue = (E) ArrayList.this.elementData[offset + index]; 975 ArrayList.this.elementData[offset + index] = e; 976 return oldValue; 977 } 978 979 public E get(int index) { 980 if (index < 0 || index >= this.size) 981 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 982 if (ArrayList.this.modCount != this.modCount) 983 throw new ConcurrentModificationException(); 984 return (E) ArrayList.this.elementData[offset + index]; 985 } 986 987 public int size() { 988 if (ArrayList.this.modCount != this.modCount) 989 throw new ConcurrentModificationException(); 990 return this.size; 991 } 992 993 public void add(int index, E e) { 994 if (index < 0 || index > this.size) 995 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 996 if (ArrayList.this.modCount != this.modCount) 997 throw new ConcurrentModificationException(); 998 parent.add(parentOffset + index, e); 999 this.modCount = parent.modCount; 1000 this.size++; 1001 } 1002 1003 public E remove(int index) { 1004 if (index < 0 || index >= this.size) 1005 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 1006 if (ArrayList.this.modCount != this.modCount) 1007 throw new ConcurrentModificationException(); 1008 E result = parent.remove(parentOffset + index); 1009 this.modCount = parent.modCount; 1010 this.size--; 1011 return result; 1012 } 1013 1014 protected void removeRange(int fromIndex, int toIndex) { 1015 if (ArrayList.this.modCount != this.modCount) 1016 throw new ConcurrentModificationException(); 1017 parent.removeRange(parentOffset + fromIndex, 1018 parentOffset + toIndex); 1019 this.modCount = parent.modCount; 1020 this.size -= toIndex - fromIndex; 1021 } 1022 1023 public boolean addAll(Collection<? extends E> c) { 1024 return addAll(this.size, c); 1025 } 1026 1027 public boolean addAll(int index, Collection<? extends E> c) { 1028 if (index < 0 || index > this.size) 1029 throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 1030 int cSize = c.size(); 1031 if (cSize==0) 1032 return false; 1033 1034 if (ArrayList.this.modCount != this.modCount) 1035 throw new ConcurrentModificationException(); 1036 parent.addAll(parentOffset + index, c); 1037 this.modCount = parent.modCount; 1038 this.size += cSize; 1039 return true; 1040 } 1041 1042 public Iterator<E> iterator() { 1043 return listIterator(); 1044 } 1045 1046 public ListIterator<E> listIterator(final int index) { 1047 if (ArrayList.this.modCount != this.modCount) 1048 throw new ConcurrentModificationException(); 1049 if (index < 0 || index > this.size) 1050 throw new IndexOutOfBoundsException(outOfBoundsMsg(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 if (expectedModCount != ArrayList.this.modCount) 1065 throw new ConcurrentModificationException(); 1066 int i = cursor; 1067 if (i >= SubList.this.size) 1068 throw new NoSuchElementException(); 1069 Object[] elementData = ArrayList.this.elementData; 1070 if (offset + i >= elementData.length) 1071 throw new ConcurrentModificationException(); 1072 cursor = i + 1; 1073 return (E) elementData[offset + (lastRet = i)]; 1074 } 1075 1076 public boolean hasPrevious() { 1077 return cursor != 0; 1078 } 1079 1080 @SuppressWarnings("unchecked") 1081 public E previous() { 1082 if (expectedModCount != ArrayList.this.modCount) 1083 throw new ConcurrentModificationException(); 1084 int i = cursor - 1; 1085 if (i < 0) 1086 throw new NoSuchElementException(); 1087 Object[] elementData = ArrayList.this.elementData; 1088 if (offset + i >= elementData.length) 1089 throw new ConcurrentModificationException(); 1090 cursor = i; 1091 return (E) elementData[offset + (lastRet = i)]; 1092 } 1093 1094 public int nextIndex() { 1095 return cursor; 1096 } 1097 1098 public int previousIndex() { 1099 return cursor - 1; 1100 } 1101 1102 public void remove() { 1103 if (lastRet < 0) 1104 throw new IllegalStateException(); 1105 if (expectedModCount != ArrayList.this.modCount) 1106 throw new ConcurrentModificationException(); 1107 1108 try { 1109 SubList.this.remove(lastRet); 1110 cursor = lastRet; 1111 lastRet = -1; 1112 expectedModCount = ArrayList.this.modCount; 1113 } catch (IndexOutOfBoundsException ex) { 1114 throw new ConcurrentModificationException(); 1115 } 1116 } 1117 1118 public void set(E e) { 1119 if (lastRet < 0) 1120 throw new IllegalStateException(); 1121 if (expectedModCount != ArrayList.this.modCount) 1122 throw new ConcurrentModificationException(); 1123 1124 try { 1125 ArrayList.this.set(offset + lastRet, e); 1126 } catch (IndexOutOfBoundsException ex) { 1127 throw new ConcurrentModificationException(); 1128 } 1129 } 1130 1131 public void add(E e) { 1132 if (expectedModCount != ArrayList.this.modCount) 1133 throw new ConcurrentModificationException(); 1134 1135 try { 1136 int i = cursor; 1137 SubList.this.add(i, e); 1138 cursor = i + 1; 1139 lastRet = -1; 1140 expectedModCount = ArrayList.this.modCount; 1141 } catch (IndexOutOfBoundsException ex) { 1142 throw new ConcurrentModificationException(); 1143 } 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 String outOfBoundsMsg(int index) { 1154 return "Index: "+index+", Size: "+this.size; 1155 } 1156 } 1157} 1158