2 * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
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.)
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.
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
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.
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.
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>
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
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>
89 * <p>This class is a member of the
90 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
91 * Java Collections Framework</a>.
102 public class ArrayList<E> extends AbstractList<E>
103 implements List<E>, RandomAccess, Cloneable, java.io.Serializable
105 private static final long serialVersionUID = 8683452581122892189L;
108 * The array buffer into which the elements of the ArrayList are stored.
109 * The capacity of the ArrayList is the length of this array buffer.
111 private transient Object[] elementData;
114 * The size of the ArrayList (the number of elements it contains).
121 * Constructs an empty list with the specified initial capacity.
123 * @param initialCapacity the initial capacity of the list
124 * @throws IllegalArgumentException if the specified initial capacity
127 public ArrayList(int initialCapacity) {
129 if (initialCapacity < 0)
130 throw new IllegalArgumentException("Illegal Capacity: "+
132 this.elementData = new Object[initialCapacity];
136 * Constructs an empty list with an initial capacity of ten.
143 * Constructs a list containing the elements of the specified
144 * collection, in the order they are returned by the collection's
147 * @param c the collection whose elements are to be placed into this list
148 * @throws NullPointerException if the specified collection is null
150 public ArrayList(Collection<? extends E> c) {
151 elementData = c.toArray();
152 size = elementData.length;
153 // c.toArray might (incorrectly) not return Object[] (see 6260652)
154 if (elementData.getClass() != Object[].class)
155 elementData = Arrays.copyOf(elementData, size, Object[].class);
159 * Trims the capacity of this <tt>ArrayList</tt> instance to be the
160 * list's current size. An application can use this operation to minimize
161 * the storage of an <tt>ArrayList</tt> instance.
163 public void trimToSize() {
165 int oldCapacity = elementData.length;
166 if (size < oldCapacity) {
167 elementData = Arrays.copyOf(elementData, size);
172 * Increases the capacity of this <tt>ArrayList</tt> instance, if
173 * necessary, to ensure that it can hold at least the number of elements
174 * specified by the minimum capacity argument.
176 * @param minCapacity the desired minimum capacity
178 public void ensureCapacity(int minCapacity) {
180 ensureCapacityInternal(minCapacity);
183 private void ensureCapacityInternal(int minCapacity) {
185 // overflow-conscious code
186 if (minCapacity - elementData.length > 0)
191 * The maximum size of array to allocate.
192 * Some VMs reserve some header words in an array.
193 * Attempts to allocate larger arrays may result in
194 * OutOfMemoryError: Requested array size exceeds VM limit
196 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
199 * Increases the capacity to ensure that it can hold at least the
200 * number of elements specified by the minimum capacity argument.
202 * @param minCapacity the desired minimum capacity
204 private void grow(int minCapacity) {
205 // overflow-conscious code
206 int oldCapacity = elementData.length;
207 int newCapacity = oldCapacity + (oldCapacity >> 1);
208 if (newCapacity - minCapacity < 0)
209 newCapacity = minCapacity;
210 if (newCapacity - MAX_ARRAY_SIZE > 0)
211 newCapacity = hugeCapacity(minCapacity);
212 // minCapacity is usually close to size, so this is a win:
213 elementData = Arrays.copyOf(elementData, newCapacity);
216 private static int hugeCapacity(int minCapacity) {
217 if (minCapacity < 0) // overflow
218 throw new OutOfMemoryError();
219 return (minCapacity > MAX_ARRAY_SIZE) ?
225 * Returns the number of elements in this list.
227 * @return the number of elements in this list
234 * Returns <tt>true</tt> if this list contains no elements.
236 * @return <tt>true</tt> if this list contains no elements
238 public boolean isEmpty() {
243 * Returns <tt>true</tt> if this list contains the specified element.
244 * More formally, returns <tt>true</tt> if and only if this list contains
245 * at least one element <tt>e</tt> such that
246 * <tt>(o==null ? e==null : o.equals(e))</tt>.
248 * @param o element whose presence in this list is to be tested
249 * @return <tt>true</tt> if this list contains the specified element
251 public boolean contains(Object o) {
252 return indexOf(o) >= 0;
256 * Returns the index of the first occurrence of the specified element
257 * in this list, or -1 if this list does not contain the element.
258 * More formally, returns the lowest index <tt>i</tt> such that
259 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
260 * or -1 if there is no such index.
262 public int indexOf(Object o) {
264 for (int i = 0; i < size; i++)
265 if (elementData[i]==null)
268 for (int i = 0; i < size; i++)
269 if (o.equals(elementData[i]))
276 * Returns the index of the last occurrence of the specified element
277 * in this list, or -1 if this list does not contain the element.
278 * More formally, returns the highest index <tt>i</tt> such that
279 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
280 * or -1 if there is no such index.
282 public int lastIndexOf(Object o) {
284 for (int i = size-1; i >= 0; i--)
285 if (elementData[i]==null)
288 for (int i = size-1; i >= 0; i--)
289 if (o.equals(elementData[i]))
296 * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
297 * elements themselves are not copied.)
299 * @return a clone of this <tt>ArrayList</tt> instance
301 public Object clone() {
303 @SuppressWarnings("unchecked")
304 ArrayList<E> v = (ArrayList<E>) super.clone();
305 v.elementData = Arrays.copyOf(elementData, size);
308 } catch (CloneNotSupportedException e) {
309 // this shouldn't happen, since we are Cloneable
310 throw new InternalError();
315 * Returns an array containing all of the elements in this list
316 * in proper sequence (from first to last element).
318 * <p>The returned array will be "safe" in that no references to it are
319 * maintained by this list. (In other words, this method must allocate
320 * a new array). The caller is thus free to modify the returned array.
322 * <p>This method acts as bridge between array-based and collection-based
325 * @return an array containing all of the elements in this list in
328 public Object[] toArray() {
329 return Arrays.copyOf(elementData, size);
333 * Returns an array containing all of the elements in this list in proper
334 * sequence (from first to last element); the runtime type of the returned
335 * array is that of the specified array. If the list fits in the
336 * specified array, it is returned therein. Otherwise, a new array is
337 * allocated with the runtime type of the specified array and the size of
340 * <p>If the list fits in the specified array with room to spare
341 * (i.e., the array has more elements than the list), the element in
342 * the array immediately following the end of the collection is set to
343 * <tt>null</tt>. (This is useful in determining the length of the
344 * list <i>only</i> if the caller knows that the list does not contain
345 * any null elements.)
347 * @param a the array into which the elements of the list are to
348 * be stored, if it is big enough; otherwise, a new array of the
349 * same runtime type is allocated for this purpose.
350 * @return an array containing the elements of the list
351 * @throws ArrayStoreException if the runtime type of the specified array
352 * is not a supertype of the runtime type of every element in
354 * @throws NullPointerException if the specified array is null
356 @SuppressWarnings("unchecked")
357 public <T> T[] toArray(T[] a) {
359 // Make a new array of a's runtime type, but my contents:
360 return (T[]) Arrays.copyOf(elementData, size, a.getClass());
361 System.arraycopy(elementData, 0, a, 0, size);
367 // Positional Access Operations
369 @SuppressWarnings("unchecked")
370 E elementData(int index) {
371 return (E) elementData[index];
375 * Returns the element at the specified position in this list.
377 * @param index index of the element to return
378 * @return the element at the specified position in this list
379 * @throws IndexOutOfBoundsException {@inheritDoc}
381 public E get(int index) {
384 return elementData(index);
388 * Replaces the element at the specified position in this list with
389 * the specified element.
391 * @param index index of the element to replace
392 * @param element element to be stored at the specified position
393 * @return the element previously at the specified position
394 * @throws IndexOutOfBoundsException {@inheritDoc}
396 public E set(int index, E element) {
399 E oldValue = elementData(index);
400 elementData[index] = element;
405 * Appends the specified element to the end of this list.
407 * @param e element to be appended to this list
408 * @return <tt>true</tt> (as specified by {@link Collection#add})
410 public boolean add(E e) {
411 ensureCapacityInternal(size + 1); // Increments modCount!!
412 elementData[size++] = e;
417 * Inserts the specified element at the specified position in this
418 * list. Shifts the element currently at that position (if any) and
419 * any subsequent elements to the right (adds one to their indices).
421 * @param index index at which the specified element is to be inserted
422 * @param element element to be inserted
423 * @throws IndexOutOfBoundsException {@inheritDoc}
425 public void add(int index, E element) {
426 rangeCheckForAdd(index);
428 ensureCapacityInternal(size + 1); // Increments modCount!!
429 System.arraycopy(elementData, index, elementData, index + 1,
431 elementData[index] = element;
436 * Removes the element at the specified position in this list.
437 * Shifts any subsequent elements to the left (subtracts one from their
440 * @param index the index of the element to be removed
441 * @return the element that was removed from the list
442 * @throws IndexOutOfBoundsException {@inheritDoc}
444 public E remove(int index) {
448 E oldValue = elementData(index);
450 int numMoved = size - index - 1;
452 System.arraycopy(elementData, index+1, elementData, index,
454 elementData[--size] = null; // Let gc do its work
460 * Removes the first occurrence of the specified element from this list,
461 * if it is present. If the list does not contain the element, it is
462 * unchanged. More formally, removes the element with the lowest index
463 * <tt>i</tt> such that
464 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
465 * (if such an element exists). Returns <tt>true</tt> if this list
466 * contained the specified element (or equivalently, if this list
467 * changed as a result of the call).
469 * @param o element to be removed from this list, if present
470 * @return <tt>true</tt> if this list contained the specified element
472 public boolean remove(Object o) {
474 for (int index = 0; index < size; index++)
475 if (elementData[index] == null) {
480 for (int index = 0; index < size; index++)
481 if (o.equals(elementData[index])) {
490 * Private remove method that skips bounds checking and does not
491 * return the value removed.
493 private void fastRemove(int index) {
495 int numMoved = size - index - 1;
497 System.arraycopy(elementData, index+1, elementData, index,
499 elementData[--size] = null; // Let gc do its work
503 * Removes all of the elements from this list. The list will
504 * be empty after this call returns.
506 public void clear() {
509 // Let gc do its work
510 for (int i = 0; i < size; i++)
511 elementData[i] = null;
517 * Appends all of the elements in the specified collection to the end of
518 * this list, in the order that they are returned by the
519 * specified collection's Iterator. The behavior of this operation is
520 * undefined if the specified collection is modified while the operation
521 * is in progress. (This implies that the behavior of this call is
522 * undefined if the specified collection is this list, and this
525 * @param c collection containing elements to be added to this list
526 * @return <tt>true</tt> if this list changed as a result of the call
527 * @throws NullPointerException if the specified collection is null
529 public boolean addAll(Collection<? extends E> c) {
530 Object[] a = c.toArray();
531 int numNew = a.length;
532 ensureCapacityInternal(size + numNew); // Increments modCount
533 System.arraycopy(a, 0, elementData, size, numNew);
539 * Inserts all of the elements in the specified collection into this
540 * list, starting at the specified position. Shifts the element
541 * currently at that position (if any) and any subsequent elements to
542 * the right (increases their indices). The new elements will appear
543 * in the list in the order that they are returned by the
544 * specified collection's iterator.
546 * @param index index at which to insert the first element from the
547 * specified collection
548 * @param c collection containing elements to be added to this list
549 * @return <tt>true</tt> if this list changed as a result of the call
550 * @throws IndexOutOfBoundsException {@inheritDoc}
551 * @throws NullPointerException if the specified collection is null
553 public boolean addAll(int index, Collection<? extends E> c) {
554 rangeCheckForAdd(index);
556 Object[] a = c.toArray();
557 int numNew = a.length;
558 ensureCapacityInternal(size + numNew); // Increments modCount
560 int numMoved = size - index;
562 System.arraycopy(elementData, index, elementData, index + numNew,
565 System.arraycopy(a, 0, elementData, index, numNew);
571 * Removes from this list all of the elements whose index is between
572 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
573 * Shifts any succeeding elements to the left (reduces their index).
574 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
575 * (If {@code toIndex==fromIndex}, this operation has no effect.)
577 * @throws IndexOutOfBoundsException if {@code fromIndex} or
578 * {@code toIndex} is out of range
579 * ({@code fromIndex < 0 ||
580 * fromIndex >= size() ||
581 * toIndex > size() ||
582 * toIndex < fromIndex})
584 protected void removeRange(int fromIndex, int toIndex) {
586 int numMoved = size - toIndex;
587 System.arraycopy(elementData, toIndex, elementData, fromIndex,
590 // Let gc do its work
591 int newSize = size - (toIndex-fromIndex);
592 while (size != newSize)
593 elementData[--size] = null;
597 * Checks if the given index is in range. If not, throws an appropriate
598 * runtime exception. This method does *not* check if the index is
599 * negative: It is always used immediately prior to an array access,
600 * which throws an ArrayIndexOutOfBoundsException if index is negative.
602 private void rangeCheck(int index) {
604 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
608 * A version of rangeCheck used by add and addAll.
610 private void rangeCheckForAdd(int index) {
611 if (index > size || index < 0)
612 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
616 * Constructs an IndexOutOfBoundsException detail message.
617 * Of the many possible refactorings of the error handling code,
618 * this "outlining" performs best with both server and client VMs.
620 private String outOfBoundsMsg(int index) {
621 return "Index: "+index+", Size: "+size;
625 * Removes from this list all of its elements that are contained in the
626 * specified collection.
628 * @param c collection containing elements to be removed from this list
629 * @return {@code true} if this list changed as a result of the call
630 * @throws ClassCastException if the class of an element of this list
631 * is incompatible with the specified collection
632 * (<a href="Collection.html#optional-restrictions">optional</a>)
633 * @throws NullPointerException if this list contains a null element and the
634 * specified collection does not permit null elements
635 * (<a href="Collection.html#optional-restrictions">optional</a>),
636 * or if the specified collection is null
637 * @see Collection#contains(Object)
639 public boolean removeAll(Collection<?> c) {
640 return batchRemove(c, false);
644 * Retains only the elements in this list that are contained in the
645 * specified collection. In other words, removes from this list all
646 * of its elements that are not contained in the specified collection.
648 * @param c collection containing elements to be retained in this list
649 * @return {@code true} if this list changed as a result of the call
650 * @throws ClassCastException if the class of an element of this list
651 * is incompatible with the specified collection
652 * (<a href="Collection.html#optional-restrictions">optional</a>)
653 * @throws NullPointerException if this list contains a null element and the
654 * specified collection does not permit null elements
655 * (<a href="Collection.html#optional-restrictions">optional</a>),
656 * or if the specified collection is null
657 * @see Collection#contains(Object)
659 public boolean retainAll(Collection<?> c) {
660 return batchRemove(c, true);
663 private boolean batchRemove(Collection<?> c, boolean complement) {
664 final Object[] elementData = this.elementData;
666 boolean modified = false;
668 for (; r < size; r++)
669 if (c.contains(elementData[r]) == complement)
670 elementData[w++] = elementData[r];
672 // Preserve behavioral compatibility with AbstractCollection,
673 // even if c.contains() throws.
675 System.arraycopy(elementData, r,
681 for (int i = w; i < size; i++)
682 elementData[i] = null;
683 modCount += size - w;
692 * Save the state of the <tt>ArrayList</tt> instance to a stream (that
695 * @serialData The length of the array backing the <tt>ArrayList</tt>
696 * instance is emitted (int), followed by all of its elements
697 * (each an <tt>Object</tt>) in the proper order.
699 private void writeObject(java.io.ObjectOutputStream s)
700 throws java.io.IOException{
701 // Write out element count, and any hidden stuff
702 int expectedModCount = modCount;
703 s.defaultWriteObject();
705 // Write out array length
706 s.writeInt(elementData.length);
708 // Write out all elements in the proper order.
709 for (int i=0; i<size; i++)
710 s.writeObject(elementData[i]);
712 if (modCount != expectedModCount) {
713 throw new ConcurrentModificationException();
719 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
722 private void readObject(java.io.ObjectInputStream s)
723 throws java.io.IOException, ClassNotFoundException {
724 // Read in size, and any hidden stuff
725 s.defaultReadObject();
727 // Read in array length and allocate array
728 int arrayLength = s.readInt();
729 Object[] a = elementData = new Object[arrayLength];
731 // Read in all elements in the proper order.
732 for (int i=0; i<size; i++)
733 a[i] = s.readObject();
737 * Returns a list iterator over the elements in this list (in proper
738 * sequence), starting at the specified position in the list.
739 * The specified index indicates the first element that would be
740 * returned by an initial call to {@link ListIterator#next next}.
741 * An initial call to {@link ListIterator#previous previous} would
742 * return the element with the specified index minus one.
744 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
746 * @throws IndexOutOfBoundsException {@inheritDoc}
748 public ListIterator<E> listIterator(int index) {
749 if (index < 0 || index > size)
750 throw new IndexOutOfBoundsException("Index: "+index);
751 return new ListItr(index);
755 * Returns a list iterator over the elements in this list (in proper
758 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
760 * @see #listIterator(int)
762 public ListIterator<E> listIterator() {
763 return new ListItr(0);
767 * Returns an iterator over the elements in this list in proper sequence.
769 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
771 * @return an iterator over the elements in this list in proper sequence
773 public Iterator<E> iterator() {
778 * An optimized version of AbstractList.Itr
780 private class Itr implements Iterator<E> {
781 int cursor; // index of next element to return
782 int lastRet = -1; // index of last element returned; -1 if no such
783 int expectedModCount = modCount;
785 public boolean hasNext() {
786 return cursor != size;
789 @SuppressWarnings("unchecked")
791 checkForComodification();
794 throw new NoSuchElementException();
795 Object[] elementData = ArrayList.this.elementData;
796 if (i >= elementData.length)
797 throw new ConcurrentModificationException();
799 return (E) elementData[lastRet = i];
802 public void remove() {
804 throw new IllegalStateException();
805 checkForComodification();
808 ArrayList.this.remove(lastRet);
811 expectedModCount = modCount;
812 } catch (IndexOutOfBoundsException ex) {
813 throw new ConcurrentModificationException();
817 final void checkForComodification() {
818 if (modCount != expectedModCount)
819 throw new ConcurrentModificationException();
824 * An optimized version of AbstractList.ListItr
826 private class ListItr extends Itr implements ListIterator<E> {
832 public boolean hasPrevious() {
836 public int nextIndex() {
840 public int previousIndex() {
844 @SuppressWarnings("unchecked")
845 public E previous() {
846 checkForComodification();
849 throw new NoSuchElementException();
850 Object[] elementData = ArrayList.this.elementData;
851 if (i >= elementData.length)
852 throw new ConcurrentModificationException();
854 return (E) elementData[lastRet = i];
857 public void set(E e) {
859 throw new IllegalStateException();
860 checkForComodification();
863 ArrayList.this.set(lastRet, e);
864 } catch (IndexOutOfBoundsException ex) {
865 throw new ConcurrentModificationException();
869 public void add(E e) {
870 checkForComodification();
874 ArrayList.this.add(i, e);
877 expectedModCount = modCount;
878 } catch (IndexOutOfBoundsException ex) {
879 throw new ConcurrentModificationException();
885 * Returns a view of the portion of this list between the specified
886 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
887 * {@code fromIndex} and {@code toIndex} are equal, the returned list is
888 * empty.) The returned list is backed by this list, so non-structural
889 * changes in the returned list are reflected in this list, and vice-versa.
890 * The returned list supports all of the optional list operations.
892 * <p>This method eliminates the need for explicit range operations (of
893 * the sort that commonly exist for arrays). Any operation that expects
894 * a list can be used as a range operation by passing a subList view
895 * instead of a whole list. For example, the following idiom
896 * removes a range of elements from a list:
898 * list.subList(from, to).clear();
900 * Similar idioms may be constructed for {@link #indexOf(Object)} and
901 * {@link #lastIndexOf(Object)}, and all of the algorithms in the
902 * {@link Collections} class can be applied to a subList.
904 * <p>The semantics of the list returned by this method become undefined if
905 * the backing list (i.e., this list) is <i>structurally modified</i> in
906 * any way other than via the returned list. (Structural modifications are
907 * those that change the size of this list, or otherwise perturb it in such
908 * a fashion that iterations in progress may yield incorrect results.)
910 * @throws IndexOutOfBoundsException {@inheritDoc}
911 * @throws IllegalArgumentException {@inheritDoc}
913 public List<E> subList(int fromIndex, int toIndex) {
914 subListRangeCheck(fromIndex, toIndex, size);
915 return new SubList(this, 0, fromIndex, toIndex);
918 static void subListRangeCheck(int fromIndex, int toIndex, int size) {
920 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
922 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
923 if (fromIndex > toIndex)
924 throw new IllegalArgumentException("fromIndex(" + fromIndex +
925 ") > toIndex(" + toIndex + ")");
928 private class SubList extends AbstractList<E> implements RandomAccess {
929 private final AbstractList<E> parent;
930 private final int parentOffset;
931 private final int offset;
934 SubList(AbstractList<E> parent,
935 int offset, int fromIndex, int toIndex) {
936 this.parent = parent;
937 this.parentOffset = fromIndex;
938 this.offset = offset + fromIndex;
939 this.size = toIndex - fromIndex;
940 this.modCount = ArrayList.this.modCount;
943 public E set(int index, E e) {
945 checkForComodification();
946 E oldValue = ArrayList.this.elementData(offset + index);
947 ArrayList.this.elementData[offset + index] = e;
951 public E get(int index) {
953 checkForComodification();
954 return ArrayList.this.elementData(offset + index);
958 checkForComodification();
962 public void add(int index, E e) {
963 rangeCheckForAdd(index);
964 checkForComodification();
965 parent.add(parentOffset + index, e);
966 this.modCount = parent.modCount;
970 public E remove(int index) {
972 checkForComodification();
973 E result = parent.remove(parentOffset + index);
974 this.modCount = parent.modCount;
979 protected void removeRange(int fromIndex, int toIndex) {
980 checkForComodification();
981 parent.removeRange(parentOffset + fromIndex,
982 parentOffset + toIndex);
983 this.modCount = parent.modCount;
984 this.size -= toIndex - fromIndex;
987 public boolean addAll(Collection<? extends E> c) {
988 return addAll(this.size, c);
991 public boolean addAll(int index, Collection<? extends E> c) {
992 rangeCheckForAdd(index);
993 int cSize = c.size();
997 checkForComodification();
998 parent.addAll(parentOffset + index, c);
999 this.modCount = parent.modCount;
1004 public Iterator<E> iterator() {
1005 return listIterator();
1008 public ListIterator<E> listIterator(final int index) {
1009 checkForComodification();
1010 rangeCheckForAdd(index);
1011 final int offset = this.offset;
1013 return new ListIterator<E>() {
1016 int expectedModCount = ArrayList.this.modCount;
1018 public boolean hasNext() {
1019 return cursor != SubList.this.size;
1022 @SuppressWarnings("unchecked")
1024 checkForComodification();
1026 if (i >= SubList.this.size)
1027 throw new NoSuchElementException();
1028 Object[] elementData = ArrayList.this.elementData;
1029 if (offset + i >= elementData.length)
1030 throw new ConcurrentModificationException();
1032 return (E) elementData[offset + (lastRet = i)];
1035 public boolean hasPrevious() {
1039 @SuppressWarnings("unchecked")
1040 public E previous() {
1041 checkForComodification();
1044 throw new NoSuchElementException();
1045 Object[] elementData = ArrayList.this.elementData;
1046 if (offset + i >= elementData.length)
1047 throw new ConcurrentModificationException();
1049 return (E) elementData[offset + (lastRet = i)];
1052 public int nextIndex() {
1056 public int previousIndex() {
1060 public void remove() {
1062 throw new IllegalStateException();
1063 checkForComodification();
1066 SubList.this.remove(lastRet);
1069 expectedModCount = ArrayList.this.modCount;
1070 } catch (IndexOutOfBoundsException ex) {
1071 throw new ConcurrentModificationException();
1075 public void set(E e) {
1077 throw new IllegalStateException();
1078 checkForComodification();
1081 ArrayList.this.set(offset + lastRet, e);
1082 } catch (IndexOutOfBoundsException ex) {
1083 throw new ConcurrentModificationException();
1087 public void add(E e) {
1088 checkForComodification();
1092 SubList.this.add(i, e);
1095 expectedModCount = ArrayList.this.modCount;
1096 } catch (IndexOutOfBoundsException ex) {
1097 throw new ConcurrentModificationException();
1101 final void checkForComodification() {
1102 if (expectedModCount != ArrayList.this.modCount)
1103 throw new ConcurrentModificationException();
1108 public List<E> subList(int fromIndex, int toIndex) {
1109 subListRangeCheck(fromIndex, toIndex, size);
1110 return new SubList(this, offset, fromIndex, toIndex);
1113 private void rangeCheck(int index) {
1114 if (index < 0 || index >= this.size)
1115 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1118 private void rangeCheckForAdd(int index) {
1119 if (index < 0 || index > this.size)
1120 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1123 private String outOfBoundsMsg(int index) {
1124 return "Index: "+index+", Size: "+this.size;
1127 private void checkForComodification() {
1128 if (ArrayList.this.modCount != this.modCount)
1129 throw new ConcurrentModificationException();