Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
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
30 * Resizable-array implementation of the <tt>List</tt> interface. Implements
31 * all optional list operations, and permits all elements, including
32 * <tt>null</tt>. In addition to implementing the <tt>List</tt> interface,
33 * this class provides methods to manipulate the size of the array that is
34 * used internally to store the list. (This class is roughly equivalent to
35 * <tt>Vector</tt>, except that it is unsynchronized.)
37 * <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
38 * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
39 * time. The <tt>add</tt> operation runs in <i>amortized constant time</i>,
40 * that is, adding n elements requires O(n) time. All of the other operations
41 * run in linear time (roughly speaking). The constant factor is low compared
42 * to that for the <tt>LinkedList</tt> implementation.
44 * <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is
45 * the size of the array used to store the elements in the list. It is always
46 * at least as large as the list size. As elements are added to an ArrayList,
47 * its capacity grows automatically. The details of the growth policy are not
48 * specified beyond the fact that adding an element has constant amortized
51 * <p>An application can increase the capacity of an <tt>ArrayList</tt> instance
52 * before adding a large number of elements using the <tt>ensureCapacity</tt>
53 * operation. This may reduce the amount of incremental reallocation.
55 * <p><strong>Note that this implementation is not synchronized.</strong>
56 * If multiple threads access an <tt>ArrayList</tt> instance concurrently,
57 * and at least one of the threads modifies the list structurally, it
58 * <i>must</i> be synchronized externally. (A structural modification is
59 * any operation that adds or deletes one or more elements, or explicitly
60 * resizes the backing array; merely setting the value of an element is not
61 * a structural modification.) This is typically accomplished by
62 * synchronizing on some object that naturally encapsulates the list.
64 * If no such object exists, the list should be "wrapped" using the
65 * {@link Collections#synchronizedList Collections.synchronizedList}
66 * method. This is best done at creation time, to prevent accidental
67 * unsynchronized access to the list:<pre>
68 * List list = Collections.synchronizedList(new ArrayList(...));</pre>
70 * <p><a name="fail-fast"/>
71 * The iterators returned by this class's {@link #iterator() iterator} and
72 * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
73 * if the list is structurally modified at any time after the iterator is
74 * created, in any way except through the iterator's own
75 * {@link ListIterator#remove() remove} or
76 * {@link ListIterator#add(Object) add} methods, the iterator will throw a
77 * {@link ConcurrentModificationException}. Thus, in the face of
78 * concurrent modification, the iterator fails quickly and cleanly, rather
79 * than risking arbitrary, non-deterministic behavior at an undetermined
82 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
83 * as it is, generally speaking, impossible to make any hard guarantees in the
84 * presence of unsynchronized concurrent modification. Fail-fast iterators
85 * throw {@code ConcurrentModificationException} on a best-effort basis.
86 * Therefore, it would be wrong to write a program that depended on this
87 * exception for its correctness: <i>the fail-fast behavior of iterators
88 * should be used only to detect bugs.</i>
90 * <p>This class is a member of the
91 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
92 * Java Collections Framework</a>.
103 public class ArrayList<E> extends AbstractList<E>
104 implements List<E>, RandomAccess, Cloneable, java.io.Serializable
106 private static final long serialVersionUID = 8683452581122892189L;
109 * The array buffer into which the elements of the ArrayList are stored.
110 * The capacity of the ArrayList is the length of this array buffer.
112 private transient Object[] elementData;
115 * The size of the ArrayList (the number of elements it contains).
122 * Constructs an empty list with the specified initial capacity.
124 * @param initialCapacity the initial capacity of the list
125 * @throws IllegalArgumentException if the specified initial capacity
128 public ArrayList(int initialCapacity) {
130 if (initialCapacity < 0)
131 throw new IllegalArgumentException("Illegal Capacity: "+
133 this.elementData = new Object[initialCapacity];
137 * Constructs an empty list with an initial capacity of ten.
144 * Constructs a list containing the elements of the specified
145 * collection, in the order they are returned by the collection's
148 * @param c the collection whose elements are to be placed into this list
149 * @throws NullPointerException if the specified collection is null
151 public ArrayList(Collection<? extends E> c) {
152 elementData = c.toArray();
153 size = elementData.length;
154 // c.toArray might (incorrectly) not return Object[] (see 6260652)
155 if (elementData.getClass() != Object[].class)
156 elementData = Arrays.copyOf(elementData, size, Object[].class);
160 * Trims the capacity of this <tt>ArrayList</tt> instance to be the
161 * list's current size. An application can use this operation to minimize
162 * the storage of an <tt>ArrayList</tt> instance.
164 public void trimToSize() {
166 int oldCapacity = elementData.length;
167 if (size < oldCapacity) {
168 elementData = Arrays.copyOf(elementData, size);
173 * Increases the capacity of this <tt>ArrayList</tt> instance, if
174 * necessary, to ensure that it can hold at least the number of elements
175 * specified by the minimum capacity argument.
177 * @param minCapacity the desired minimum capacity
179 public void ensureCapacity(int minCapacity) {
181 ensureCapacityInternal(minCapacity);
184 private void ensureCapacityInternal(int minCapacity) {
186 // overflow-conscious code
187 if (minCapacity - elementData.length > 0)
192 * The maximum size of array to allocate.
193 * Some VMs reserve some header words in an array.
194 * Attempts to allocate larger arrays may result in
195 * OutOfMemoryError: Requested array size exceeds VM limit
197 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
200 * Increases the capacity to ensure that it can hold at least the
201 * number of elements specified by the minimum capacity argument.
203 * @param minCapacity the desired minimum capacity
205 private void grow(int minCapacity) {
206 // overflow-conscious code
207 int oldCapacity = elementData.length;
208 int newCapacity = oldCapacity + (oldCapacity >> 1);
209 if (newCapacity - minCapacity < 0)
210 newCapacity = minCapacity;
211 if (newCapacity - MAX_ARRAY_SIZE > 0)
212 newCapacity = hugeCapacity(minCapacity);
213 // minCapacity is usually close to size, so this is a win:
214 elementData = Arrays.copyOf(elementData, newCapacity);
217 private static int hugeCapacity(int minCapacity) {
218 if (minCapacity < 0) // overflow
219 throw new OutOfMemoryError();
220 return (minCapacity > MAX_ARRAY_SIZE) ?
226 * Returns the number of elements in this list.
228 * @return the number of elements in this list
235 * Returns <tt>true</tt> if this list contains no elements.
237 * @return <tt>true</tt> if this list contains no elements
239 public boolean isEmpty() {
244 * Returns <tt>true</tt> if this list contains the specified element.
245 * More formally, returns <tt>true</tt> if and only if this list contains
246 * at least one element <tt>e</tt> such that
247 * <tt>(o==null ? e==null : o.equals(e))</tt>.
249 * @param o element whose presence in this list is to be tested
250 * @return <tt>true</tt> if this list contains the specified element
252 public boolean contains(Object o) {
253 return indexOf(o) >= 0;
257 * Returns the index of the first occurrence of the specified element
258 * in this list, or -1 if this list does not contain the element.
259 * More formally, returns the lowest index <tt>i</tt> such that
260 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
261 * or -1 if there is no such index.
263 public int indexOf(Object o) {
265 for (int i = 0; i < size; i++)
266 if (elementData[i]==null)
269 for (int i = 0; i < size; i++)
270 if (o.equals(elementData[i]))
277 * Returns the index of the last occurrence of the specified element
278 * in this list, or -1 if this list does not contain the element.
279 * More formally, returns the highest index <tt>i</tt> such that
280 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
281 * or -1 if there is no such index.
283 public int lastIndexOf(Object o) {
285 for (int i = size-1; i >= 0; i--)
286 if (elementData[i]==null)
289 for (int i = size-1; i >= 0; i--)
290 if (o.equals(elementData[i]))
297 * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
298 * elements themselves are not copied.)
300 * @return a clone of this <tt>ArrayList</tt> instance
302 public Object clone() {
304 @SuppressWarnings("unchecked")
305 ArrayList<E> v = (ArrayList<E>) super.clone();
306 v.elementData = Arrays.copyOf(elementData, size);
309 } catch (CloneNotSupportedException e) {
310 // this shouldn't happen, since we are Cloneable
311 throw new InternalError();
316 * Returns an array containing all of the elements in this list
317 * in proper sequence (from first to last element).
319 * <p>The returned array will be "safe" in that no references to it are
320 * maintained by this list. (In other words, this method must allocate
321 * a new array). The caller is thus free to modify the returned array.
323 * <p>This method acts as bridge between array-based and collection-based
326 * @return an array containing all of the elements in this list in
329 public Object[] toArray() {
330 return Arrays.copyOf(elementData, size);
334 * Returns an array containing all of the elements in this list in proper
335 * sequence (from first to last element); the runtime type of the returned
336 * array is that of the specified array. If the list fits in the
337 * specified array, it is returned therein. Otherwise, a new array is
338 * allocated with the runtime type of the specified array and the size of
341 * <p>If the list fits in the specified array with room to spare
342 * (i.e., the array has more elements than the list), the element in
343 * the array immediately following the end of the collection is set to
344 * <tt>null</tt>. (This is useful in determining the length of the
345 * list <i>only</i> if the caller knows that the list does not contain
346 * any null elements.)
348 * @param a the array into which the elements of the list are to
349 * be stored, if it is big enough; otherwise, a new array of the
350 * same runtime type is allocated for this purpose.
351 * @return an array containing the elements of the list
352 * @throws ArrayStoreException if the runtime type of the specified array
353 * is not a supertype of the runtime type of every element in
355 * @throws NullPointerException if the specified array is null
357 @SuppressWarnings("unchecked")
358 public <T> T[] toArray(T[] a) {
360 // Make a new array of a's runtime type, but my contents:
361 return (T[]) Arrays.copyOf(elementData, size, a.getClass());
362 System.arraycopy(elementData, 0, a, 0, size);
368 // Positional Access Operations
370 @SuppressWarnings("unchecked")
371 E elementData(int index) {
372 return (E) elementData[index];
376 * Returns the element at the specified position in this list.
378 * @param index index of the element to return
379 * @return the element at the specified position in this list
380 * @throws IndexOutOfBoundsException {@inheritDoc}
382 public E get(int index) {
385 return elementData(index);
389 * Replaces the element at the specified position in this list with
390 * the specified element.
392 * @param index index of the element to replace
393 * @param element element to be stored at the specified position
394 * @return the element previously at the specified position
395 * @throws IndexOutOfBoundsException {@inheritDoc}
397 public E set(int index, E element) {
400 E oldValue = elementData(index);
401 elementData[index] = element;
406 * Appends the specified element to the end of this list.
408 * @param e element to be appended to this list
409 * @return <tt>true</tt> (as specified by {@link Collection#add})
411 public boolean add(E e) {
412 ensureCapacityInternal(size + 1); // Increments modCount!!
413 elementData[size++] = e;
418 * Inserts the specified element at the specified position in this
419 * list. Shifts the element currently at that position (if any) and
420 * any subsequent elements to the right (adds one to their indices).
422 * @param index index at which the specified element is to be inserted
423 * @param element element to be inserted
424 * @throws IndexOutOfBoundsException {@inheritDoc}
426 public void add(int index, E element) {
427 rangeCheckForAdd(index);
429 ensureCapacityInternal(size + 1); // Increments modCount!!
430 System.arraycopy(elementData, index, elementData, index + 1,
432 elementData[index] = element;
437 * Removes the element at the specified position in this list.
438 * Shifts any subsequent elements to the left (subtracts one from their
441 * @param index the index of the element to be removed
442 * @return the element that was removed from the list
443 * @throws IndexOutOfBoundsException {@inheritDoc}
445 public E remove(int index) {
449 E oldValue = elementData(index);
451 int numMoved = size - index - 1;
453 System.arraycopy(elementData, index+1, elementData, index,
455 elementData[--size] = null; // Let gc do its work
461 * Removes the first occurrence of the specified element from this list,
462 * if it is present. If the list does not contain the element, it is
463 * unchanged. More formally, removes the element with the lowest index
464 * <tt>i</tt> such that
465 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
466 * (if such an element exists). Returns <tt>true</tt> if this list
467 * contained the specified element (or equivalently, if this list
468 * changed as a result of the call).
470 * @param o element to be removed from this list, if present
471 * @return <tt>true</tt> if this list contained the specified element
473 public boolean remove(Object o) {
475 for (int index = 0; index < size; index++)
476 if (elementData[index] == null) {
481 for (int index = 0; index < size; index++)
482 if (o.equals(elementData[index])) {
491 * Private remove method that skips bounds checking and does not
492 * return the value removed.
494 private void fastRemove(int index) {
496 int numMoved = size - index - 1;
498 System.arraycopy(elementData, index+1, elementData, index,
500 elementData[--size] = null; // Let gc do its work
504 * Removes all of the elements from this list. The list will
505 * be empty after this call returns.
507 public void clear() {
510 // Let gc do its work
511 for (int i = 0; i < size; i++)
512 elementData[i] = null;
518 * Appends all of the elements in the specified collection to the end of
519 * this list, in the order that they are returned by the
520 * specified collection's Iterator. The behavior of this operation is
521 * undefined if the specified collection is modified while the operation
522 * is in progress. (This implies that the behavior of this call is
523 * undefined if the specified collection is this list, and this
526 * @param c collection containing elements to be added to this list
527 * @return <tt>true</tt> if this list changed as a result of the call
528 * @throws NullPointerException if the specified collection is null
530 public boolean addAll(Collection<? extends E> c) {
531 Object[] a = c.toArray();
532 int numNew = a.length;
533 ensureCapacityInternal(size + numNew); // Increments modCount
534 System.arraycopy(a, 0, elementData, size, numNew);
540 * Inserts all of the elements in the specified collection into this
541 * list, starting at the specified position. Shifts the element
542 * currently at that position (if any) and any subsequent elements to
543 * the right (increases their indices). The new elements will appear
544 * in the list in the order that they are returned by the
545 * specified collection's iterator.
547 * @param index index at which to insert the first element from the
548 * specified collection
549 * @param c collection containing elements to be added to this list
550 * @return <tt>true</tt> if this list changed as a result of the call
551 * @throws IndexOutOfBoundsException {@inheritDoc}
552 * @throws NullPointerException if the specified collection is null
554 public boolean addAll(int index, Collection<? extends E> c) {
555 rangeCheckForAdd(index);
557 Object[] a = c.toArray();
558 int numNew = a.length;
559 ensureCapacityInternal(size + numNew); // Increments modCount
561 int numMoved = size - index;
563 System.arraycopy(elementData, index, elementData, index + numNew,
566 System.arraycopy(a, 0, elementData, index, numNew);
572 * Removes from this list all of the elements whose index is between
573 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
574 * Shifts any succeeding elements to the left (reduces their index).
575 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
576 * (If {@code toIndex==fromIndex}, this operation has no effect.)
578 * @throws IndexOutOfBoundsException if {@code fromIndex} or
579 * {@code toIndex} is out of range
580 * ({@code fromIndex < 0 ||
581 * fromIndex >= size() ||
582 * toIndex > size() ||
583 * toIndex < fromIndex})
585 protected void removeRange(int fromIndex, int toIndex) {
587 int numMoved = size - toIndex;
588 System.arraycopy(elementData, toIndex, elementData, fromIndex,
591 // Let gc do its work
592 int newSize = size - (toIndex-fromIndex);
593 while (size != newSize)
594 elementData[--size] = null;
598 * Checks if the given index is in range. If not, throws an appropriate
599 * runtime exception. This method does *not* check if the index is
600 * negative: It is always used immediately prior to an array access,
601 * which throws an ArrayIndexOutOfBoundsException if index is negative.
603 private void rangeCheck(int index) {
605 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
609 * A version of rangeCheck used by add and addAll.
611 private void rangeCheckForAdd(int index) {
612 if (index > size || index < 0)
613 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
617 * Constructs an IndexOutOfBoundsException detail message.
618 * Of the many possible refactorings of the error handling code,
619 * this "outlining" performs best with both server and client VMs.
621 private String outOfBoundsMsg(int index) {
622 return "Index: "+index+", Size: "+size;
626 * Removes from this list all of its elements that are contained in the
627 * specified collection.
629 * @param c collection containing elements to be removed from this list
630 * @return {@code true} if this list changed as a result of the call
631 * @throws ClassCastException if the class of an element of this list
632 * is incompatible with the specified collection
633 * (<a href="Collection.html#optional-restrictions">optional</a>)
634 * @throws NullPointerException if this list contains a null element and the
635 * specified collection does not permit null elements
636 * (<a href="Collection.html#optional-restrictions">optional</a>),
637 * or if the specified collection is null
638 * @see Collection#contains(Object)
640 public boolean removeAll(Collection<?> c) {
641 return batchRemove(c, false);
645 * Retains only the elements in this list that are contained in the
646 * specified collection. In other words, removes from this list all
647 * of its elements that are not contained in the specified collection.
649 * @param c collection containing elements to be retained in this list
650 * @return {@code true} if this list changed as a result of the call
651 * @throws ClassCastException if the class of an element of this list
652 * is incompatible with the specified collection
653 * (<a href="Collection.html#optional-restrictions">optional</a>)
654 * @throws NullPointerException if this list contains a null element and the
655 * specified collection does not permit null elements
656 * (<a href="Collection.html#optional-restrictions">optional</a>),
657 * or if the specified collection is null
658 * @see Collection#contains(Object)
660 public boolean retainAll(Collection<?> c) {
661 return batchRemove(c, true);
664 private boolean batchRemove(Collection<?> c, boolean complement) {
665 final Object[] elementData = this.elementData;
667 boolean modified = false;
669 for (; r < size; r++)
670 if (c.contains(elementData[r]) == complement)
671 elementData[w++] = elementData[r];
673 // Preserve behavioral compatibility with AbstractCollection,
674 // even if c.contains() throws.
676 System.arraycopy(elementData, r,
682 for (int i = w; i < size; i++)
683 elementData[i] = null;
684 modCount += size - w;
693 * Returns a list iterator over the elements in this list (in proper
694 * sequence), starting at the specified position in the list.
695 * The specified index indicates the first element that would be
696 * returned by an initial call to {@link ListIterator#next next}.
697 * An initial call to {@link ListIterator#previous previous} would
698 * return the element with the specified index minus one.
700 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
702 * @throws IndexOutOfBoundsException {@inheritDoc}
704 public ListIterator<E> listIterator(int index) {
705 if (index < 0 || index > size)
706 throw new IndexOutOfBoundsException("Index: "+index);
707 return new ListItr(index);
711 * Returns a list iterator over the elements in this list (in proper
714 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
716 * @see #listIterator(int)
718 public ListIterator<E> listIterator() {
719 return new ListItr(0);
723 * Returns an iterator over the elements in this list in proper sequence.
725 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
727 * @return an iterator over the elements in this list in proper sequence
729 public Iterator<E> iterator() {
734 * An optimized version of AbstractList.Itr
736 private class Itr implements Iterator<E> {
737 int cursor; // index of next element to return
738 int lastRet = -1; // index of last element returned; -1 if no such
739 int expectedModCount = modCount;
741 public boolean hasNext() {
742 return cursor != size;
745 @SuppressWarnings("unchecked")
747 checkForComodification();
750 throw new NoSuchElementException();
751 Object[] elementData = ArrayList.this.elementData;
752 if (i >= elementData.length)
753 throw new ConcurrentModificationException();
755 return (E) elementData[lastRet = i];
758 public void remove() {
760 throw new IllegalStateException();
761 checkForComodification();
764 ArrayList.this.remove(lastRet);
767 expectedModCount = modCount;
768 } catch (IndexOutOfBoundsException ex) {
769 throw new ConcurrentModificationException();
773 final void checkForComodification() {
774 if (modCount != expectedModCount)
775 throw new ConcurrentModificationException();
780 * An optimized version of AbstractList.ListItr
782 private class ListItr extends Itr implements ListIterator<E> {
788 public boolean hasPrevious() {
792 public int nextIndex() {
796 public int previousIndex() {
800 @SuppressWarnings("unchecked")
801 public E previous() {
802 checkForComodification();
805 throw new NoSuchElementException();
806 Object[] elementData = ArrayList.this.elementData;
807 if (i >= elementData.length)
808 throw new ConcurrentModificationException();
810 return (E) elementData[lastRet = i];
813 public void set(E e) {
815 throw new IllegalStateException();
816 checkForComodification();
819 ArrayList.this.set(lastRet, e);
820 } catch (IndexOutOfBoundsException ex) {
821 throw new ConcurrentModificationException();
825 public void add(E e) {
826 checkForComodification();
830 ArrayList.this.add(i, e);
833 expectedModCount = modCount;
834 } catch (IndexOutOfBoundsException ex) {
835 throw new ConcurrentModificationException();
841 * Returns a view of the portion of this list between the specified
842 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
843 * {@code fromIndex} and {@code toIndex} are equal, the returned list is
844 * empty.) The returned list is backed by this list, so non-structural
845 * changes in the returned list are reflected in this list, and vice-versa.
846 * The returned list supports all of the optional list operations.
848 * <p>This method eliminates the need for explicit range operations (of
849 * the sort that commonly exist for arrays). Any operation that expects
850 * a list can be used as a range operation by passing a subList view
851 * instead of a whole list. For example, the following idiom
852 * removes a range of elements from a list:
854 * list.subList(from, to).clear();
856 * Similar idioms may be constructed for {@link #indexOf(Object)} and
857 * {@link #lastIndexOf(Object)}, and all of the algorithms in the
858 * {@link Collections} class can be applied to a subList.
860 * <p>The semantics of the list returned by this method become undefined if
861 * the backing list (i.e., this list) is <i>structurally modified</i> in
862 * any way other than via the returned list. (Structural modifications are
863 * those that change the size of this list, or otherwise perturb it in such
864 * a fashion that iterations in progress may yield incorrect results.)
866 * @throws IndexOutOfBoundsException {@inheritDoc}
867 * @throws IllegalArgumentException {@inheritDoc}
869 public List<E> subList(int fromIndex, int toIndex) {
870 subListRangeCheck(fromIndex, toIndex, size);
871 return new SubList(this, 0, fromIndex, toIndex);
874 static void subListRangeCheck(int fromIndex, int toIndex, int size) {
876 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
878 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
879 if (fromIndex > toIndex)
880 throw new IllegalArgumentException("fromIndex(" + fromIndex +
881 ") > toIndex(" + toIndex + ")");
884 private class SubList extends AbstractList<E> implements RandomAccess {
885 private final AbstractList<E> parent;
886 private final int parentOffset;
887 private final int offset;
890 SubList(AbstractList<E> parent,
891 int offset, int fromIndex, int toIndex) {
892 this.parent = parent;
893 this.parentOffset = fromIndex;
894 this.offset = offset + fromIndex;
895 this.size = toIndex - fromIndex;
896 this.modCount = ArrayList.this.modCount;
899 public E set(int index, E e) {
901 checkForComodification();
902 E oldValue = ArrayList.this.elementData(offset + index);
903 ArrayList.this.elementData[offset + index] = e;
907 public E get(int index) {
909 checkForComodification();
910 return ArrayList.this.elementData(offset + index);
914 checkForComodification();
918 public void add(int index, E e) {
919 rangeCheckForAdd(index);
920 checkForComodification();
921 parent.add(parentOffset + index, e);
922 this.modCount = parent.modCount;
926 public E remove(int index) {
928 checkForComodification();
929 E result = parent.remove(parentOffset + index);
930 this.modCount = parent.modCount;
935 protected void removeRange(int fromIndex, int toIndex) {
936 checkForComodification();
937 parent.removeRange(parentOffset + fromIndex,
938 parentOffset + toIndex);
939 this.modCount = parent.modCount;
940 this.size -= toIndex - fromIndex;
943 public boolean addAll(Collection<? extends E> c) {
944 return addAll(this.size, c);
947 public boolean addAll(int index, Collection<? extends E> c) {
948 rangeCheckForAdd(index);
949 int cSize = c.size();
953 checkForComodification();
954 parent.addAll(parentOffset + index, c);
955 this.modCount = parent.modCount;
960 public Iterator<E> iterator() {
961 return listIterator();
964 public ListIterator<E> listIterator(final int index) {
965 checkForComodification();
966 rangeCheckForAdd(index);
967 final int offset = this.offset;
969 return new ListIterator<E>() {
972 int expectedModCount = ArrayList.this.modCount;
974 public boolean hasNext() {
975 return cursor != SubList.this.size;
978 @SuppressWarnings("unchecked")
980 checkForComodification();
982 if (i >= SubList.this.size)
983 throw new NoSuchElementException();
984 Object[] elementData = ArrayList.this.elementData;
985 if (offset + i >= elementData.length)
986 throw new ConcurrentModificationException();
988 return (E) elementData[offset + (lastRet = i)];
991 public boolean hasPrevious() {
995 @SuppressWarnings("unchecked")
996 public E previous() {
997 checkForComodification();
1000 throw new NoSuchElementException();
1001 Object[] elementData = ArrayList.this.elementData;
1002 if (offset + i >= elementData.length)
1003 throw new ConcurrentModificationException();
1005 return (E) elementData[offset + (lastRet = i)];
1008 public int nextIndex() {
1012 public int previousIndex() {
1016 public void remove() {
1018 throw new IllegalStateException();
1019 checkForComodification();
1022 SubList.this.remove(lastRet);
1025 expectedModCount = ArrayList.this.modCount;
1026 } catch (IndexOutOfBoundsException ex) {
1027 throw new ConcurrentModificationException();
1031 public void set(E e) {
1033 throw new IllegalStateException();
1034 checkForComodification();
1037 ArrayList.this.set(offset + lastRet, e);
1038 } catch (IndexOutOfBoundsException ex) {
1039 throw new ConcurrentModificationException();
1043 public void add(E e) {
1044 checkForComodification();
1048 SubList.this.add(i, e);
1051 expectedModCount = ArrayList.this.modCount;
1052 } catch (IndexOutOfBoundsException ex) {
1053 throw new ConcurrentModificationException();
1057 final void checkForComodification() {
1058 if (expectedModCount != ArrayList.this.modCount)
1059 throw new ConcurrentModificationException();
1064 public List<E> subList(int fromIndex, int toIndex) {
1065 subListRangeCheck(fromIndex, toIndex, size);
1066 return new SubList(this, offset, fromIndex, toIndex);
1069 private void rangeCheck(int index) {
1070 if (index < 0 || index >= this.size)
1071 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1074 private void rangeCheckForAdd(int index) {
1075 if (index < 0 || index > this.size)
1076 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1079 private String outOfBoundsMsg(int index) {
1080 return "Index: "+index+", Size: "+this.size;
1083 private void checkForComodification() {
1084 if (ArrayList.this.modCount != this.modCount)
1085 throw new ConcurrentModificationException();