2 * Copyright (c) 1997, 2008, 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 * @exception 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 // overflow-conscious code
181 if (minCapacity - elementData.length > 0)
186 * The maximum size of array to allocate.
187 * Some VMs reserve some header words in an array.
188 * Attempts to allocate larger arrays may result in
189 * OutOfMemoryError: Requested array size exceeds VM limit
191 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
194 * Increases the capacity to ensure that it can hold at least the
195 * number of elements specified by the minimum capacity argument.
197 * @param minCapacity the desired minimum capacity
199 private void grow(int minCapacity) {
200 // overflow-conscious code
201 int oldCapacity = elementData.length;
202 int newCapacity = oldCapacity + (oldCapacity >> 1);
203 if (newCapacity - minCapacity < 0)
204 newCapacity = minCapacity;
205 if (newCapacity - MAX_ARRAY_SIZE > 0)
206 newCapacity = hugeCapacity(minCapacity);
207 // minCapacity is usually close to size, so this is a win:
208 elementData = Arrays.copyOf(elementData, newCapacity);
211 private static int hugeCapacity(int minCapacity) {
212 if (minCapacity < 0) // overflow
213 throw new OutOfMemoryError();
214 return (minCapacity > MAX_ARRAY_SIZE) ?
220 * Returns the number of elements in this list.
222 * @return the number of elements in this list
229 * Returns <tt>true</tt> if this list contains no elements.
231 * @return <tt>true</tt> if this list contains no elements
233 public boolean isEmpty() {
238 * Returns <tt>true</tt> if this list contains the specified element.
239 * More formally, returns <tt>true</tt> if and only if this list contains
240 * at least one element <tt>e</tt> such that
241 * <tt>(o==null ? e==null : o.equals(e))</tt>.
243 * @param o element whose presence in this list is to be tested
244 * @return <tt>true</tt> if this list contains the specified element
246 public boolean contains(Object o) {
247 return indexOf(o) >= 0;
251 * Returns the index of the first occurrence of the specified element
252 * in this list, or -1 if this list does not contain the element.
253 * More formally, returns the lowest index <tt>i</tt> such that
254 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
255 * or -1 if there is no such index.
257 public int indexOf(Object o) {
259 for (int i = 0; i < size; i++)
260 if (elementData[i]==null)
263 for (int i = 0; i < size; i++)
264 if (o.equals(elementData[i]))
271 * Returns the index of the last occurrence of the specified element
272 * in this list, or -1 if this list does not contain the element.
273 * More formally, returns the highest index <tt>i</tt> such that
274 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
275 * or -1 if there is no such index.
277 public int lastIndexOf(Object o) {
279 for (int i = size-1; i >= 0; i--)
280 if (elementData[i]==null)
283 for (int i = size-1; i >= 0; i--)
284 if (o.equals(elementData[i]))
291 * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
292 * elements themselves are not copied.)
294 * @return a clone of this <tt>ArrayList</tt> instance
296 public Object clone() {
298 @SuppressWarnings("unchecked")
299 ArrayList<E> v = (ArrayList<E>) super.clone();
300 v.elementData = Arrays.copyOf(elementData, size);
303 } catch (CloneNotSupportedException e) {
304 // this shouldn't happen, since we are Cloneable
305 throw new InternalError();
310 * Returns an array containing all of the elements in this list
311 * in proper sequence (from first to last element).
313 * <p>The returned array will be "safe" in that no references to it are
314 * maintained by this list. (In other words, this method must allocate
315 * a new array). The caller is thus free to modify the returned array.
317 * <p>This method acts as bridge between array-based and collection-based
320 * @return an array containing all of the elements in this list in
323 public Object[] toArray() {
324 return Arrays.copyOf(elementData, size);
328 * Returns an array containing all of the elements in this list in proper
329 * sequence (from first to last element); the runtime type of the returned
330 * array is that of the specified array. If the list fits in the
331 * specified array, it is returned therein. Otherwise, a new array is
332 * allocated with the runtime type of the specified array and the size of
335 * <p>If the list fits in the specified array with room to spare
336 * (i.e., the array has more elements than the list), the element in
337 * the array immediately following the end of the collection is set to
338 * <tt>null</tt>. (This is useful in determining the length of the
339 * list <i>only</i> if the caller knows that the list does not contain
340 * any null elements.)
342 * @param a the array into which the elements of the list are to
343 * be stored, if it is big enough; otherwise, a new array of the
344 * same runtime type is allocated for this purpose.
345 * @return an array containing the elements of the list
346 * @throws ArrayStoreException if the runtime type of the specified array
347 * is not a supertype of the runtime type of every element in
349 * @throws NullPointerException if the specified array is null
351 @SuppressWarnings("unchecked")
352 public <T> T[] toArray(T[] a) {
354 // Make a new array of a's runtime type, but my contents:
355 return (T[]) Arrays.copyOf(elementData, size, a.getClass());
356 System.arraycopy(elementData, 0, a, 0, size);
362 // Positional Access Operations
364 @SuppressWarnings("unchecked")
365 E elementData(int index) {
366 return (E) elementData[index];
370 * Returns the element at the specified position in this list.
372 * @param index index of the element to return
373 * @return the element at the specified position in this list
374 * @throws IndexOutOfBoundsException {@inheritDoc}
376 public E get(int index) {
379 return elementData(index);
383 * Replaces the element at the specified position in this list with
384 * the specified element.
386 * @param index index of the element to replace
387 * @param element element to be stored at the specified position
388 * @return the element previously at the specified position
389 * @throws IndexOutOfBoundsException {@inheritDoc}
391 public E set(int index, E element) {
394 E oldValue = elementData(index);
395 elementData[index] = element;
400 * Appends the specified element to the end of this list.
402 * @param e element to be appended to this list
403 * @return <tt>true</tt> (as specified by {@link Collection#add})
405 public boolean add(E e) {
406 ensureCapacity(size + 1); // Increments modCount!!
407 elementData[size++] = e;
412 * Inserts the specified element at the specified position in this
413 * list. Shifts the element currently at that position (if any) and
414 * any subsequent elements to the right (adds one to their indices).
416 * @param index index at which the specified element is to be inserted
417 * @param element element to be inserted
418 * @throws IndexOutOfBoundsException {@inheritDoc}
420 public void add(int index, E element) {
421 rangeCheckForAdd(index);
423 ensureCapacity(size + 1); // Increments modCount!!
424 System.arraycopy(elementData, index, elementData, index + 1,
426 elementData[index] = element;
431 * Removes the element at the specified position in this list.
432 * Shifts any subsequent elements to the left (subtracts one from their
435 * @param index the index of the element to be removed
436 * @return the element that was removed from the list
437 * @throws IndexOutOfBoundsException {@inheritDoc}
439 public E remove(int index) {
443 E oldValue = elementData(index);
445 int numMoved = size - index - 1;
447 System.arraycopy(elementData, index+1, elementData, index,
449 elementData[--size] = null; // Let gc do its work
455 * Removes the first occurrence of the specified element from this list,
456 * if it is present. If the list does not contain the element, it is
457 * unchanged. More formally, removes the element with the lowest index
458 * <tt>i</tt> such that
459 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
460 * (if such an element exists). Returns <tt>true</tt> if this list
461 * contained the specified element (or equivalently, if this list
462 * changed as a result of the call).
464 * @param o element to be removed from this list, if present
465 * @return <tt>true</tt> if this list contained the specified element
467 public boolean remove(Object o) {
469 for (int index = 0; index < size; index++)
470 if (elementData[index] == null) {
475 for (int index = 0; index < size; index++)
476 if (o.equals(elementData[index])) {
485 * Private remove method that skips bounds checking and does not
486 * return the value removed.
488 private void fastRemove(int index) {
490 int numMoved = size - index - 1;
492 System.arraycopy(elementData, index+1, elementData, index,
494 elementData[--size] = null; // Let gc do its work
498 * Removes all of the elements from this list. The list will
499 * be empty after this call returns.
501 public void clear() {
504 // Let gc do its work
505 for (int i = 0; i < size; i++)
506 elementData[i] = null;
512 * Appends all of the elements in the specified collection to the end of
513 * this list, in the order that they are returned by the
514 * specified collection's Iterator. The behavior of this operation is
515 * undefined if the specified collection is modified while the operation
516 * is in progress. (This implies that the behavior of this call is
517 * undefined if the specified collection is this list, and this
520 * @param c collection containing elements to be added to this list
521 * @return <tt>true</tt> if this list changed as a result of the call
522 * @throws NullPointerException if the specified collection is null
524 public boolean addAll(Collection<? extends E> c) {
525 Object[] a = c.toArray();
526 int numNew = a.length;
527 ensureCapacity(size + numNew); // Increments modCount
528 System.arraycopy(a, 0, elementData, size, numNew);
534 * Inserts all of the elements in the specified collection into this
535 * list, starting at the specified position. Shifts the element
536 * currently at that position (if any) and any subsequent elements to
537 * the right (increases their indices). The new elements will appear
538 * in the list in the order that they are returned by the
539 * specified collection's iterator.
541 * @param index index at which to insert the first element from the
542 * specified collection
543 * @param c collection containing elements to be added to this list
544 * @return <tt>true</tt> if this list changed as a result of the call
545 * @throws IndexOutOfBoundsException {@inheritDoc}
546 * @throws NullPointerException if the specified collection is null
548 public boolean addAll(int index, Collection<? extends E> c) {
549 rangeCheckForAdd(index);
551 Object[] a = c.toArray();
552 int numNew = a.length;
553 ensureCapacity(size + numNew); // Increments modCount
555 int numMoved = size - index;
557 System.arraycopy(elementData, index, elementData, index + numNew,
560 System.arraycopy(a, 0, elementData, index, numNew);
566 * Removes from this list all of the elements whose index is between
567 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
568 * Shifts any succeeding elements to the left (reduces their index).
569 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
570 * (If {@code toIndex==fromIndex}, this operation has no effect.)
572 * @throws IndexOutOfBoundsException if {@code fromIndex} or
573 * {@code toIndex} is out of range
574 * ({@code fromIndex < 0 ||
575 * fromIndex >= size() ||
576 * toIndex > size() ||
577 * toIndex < fromIndex})
579 protected void removeRange(int fromIndex, int toIndex) {
581 int numMoved = size - toIndex;
582 System.arraycopy(elementData, toIndex, elementData, fromIndex,
585 // Let gc do its work
586 int newSize = size - (toIndex-fromIndex);
587 while (size != newSize)
588 elementData[--size] = null;
592 * Checks if the given index is in range. If not, throws an appropriate
593 * runtime exception. This method does *not* check if the index is
594 * negative: It is always used immediately prior to an array access,
595 * which throws an ArrayIndexOutOfBoundsException if index is negative.
597 private void rangeCheck(int index) {
599 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
603 * A version of rangeCheck used by add and addAll.
605 private void rangeCheckForAdd(int index) {
606 if (index > size || index < 0)
607 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
611 * Constructs an IndexOutOfBoundsException detail message.
612 * Of the many possible refactorings of the error handling code,
613 * this "outlining" performs best with both server and client VMs.
615 private String outOfBoundsMsg(int index) {
616 return "Index: "+index+", Size: "+size;
620 * Removes from this list all of its elements that are contained in the
621 * specified collection.
623 * @param c collection containing elements to be removed from this list
624 * @return {@code true} if this list changed as a result of the call
625 * @throws ClassCastException if the class of an element of this list
626 * is incompatible with the specified collection (optional)
627 * @throws NullPointerException if this list contains a null element and the
628 * specified collection does not permit null elements (optional),
629 * or if the specified collection is null
630 * @see Collection#contains(Object)
632 public boolean removeAll(Collection<?> c) {
633 return batchRemove(c, false);
637 * Retains only the elements in this list that are contained in the
638 * specified collection. In other words, removes from this list all
639 * of its elements that are not contained in the specified collection.
641 * @param c collection containing elements to be retained in this list
642 * @return {@code true} if this list changed as a result of the call
643 * @throws ClassCastException if the class of an element of this list
644 * is incompatible with the specified collection (optional)
645 * @throws NullPointerException if this list contains a null element and the
646 * specified collection does not permit null elements (optional),
647 * or if the specified collection is null
648 * @see Collection#contains(Object)
650 public boolean retainAll(Collection<?> c) {
651 return batchRemove(c, true);
654 private boolean batchRemove(Collection<?> c, boolean complement) {
655 final Object[] elementData = this.elementData;
657 boolean modified = false;
659 for (; r < size; r++)
660 if (c.contains(elementData[r]) == complement)
661 elementData[w++] = elementData[r];
663 // Preserve behavioral compatibility with AbstractCollection,
664 // even if c.contains() throws.
666 System.arraycopy(elementData, r,
672 for (int i = w; i < size; i++)
673 elementData[i] = null;
674 modCount += size - w;
683 * Save the state of the <tt>ArrayList</tt> instance to a stream (that
686 * @serialData The length of the array backing the <tt>ArrayList</tt>
687 * instance is emitted (int), followed by all of its elements
688 * (each an <tt>Object</tt>) in the proper order.
690 private void writeObject(java.io.ObjectOutputStream s)
691 throws java.io.IOException{
692 // Write out element count, and any hidden stuff
693 int expectedModCount = modCount;
694 s.defaultWriteObject();
696 // Write out array length
697 s.writeInt(elementData.length);
699 // Write out all elements in the proper order.
700 for (int i=0; i<size; i++)
701 s.writeObject(elementData[i]);
703 if (modCount != expectedModCount) {
704 throw new ConcurrentModificationException();
710 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
713 private void readObject(java.io.ObjectInputStream s)
714 throws java.io.IOException, ClassNotFoundException {
715 // Read in size, and any hidden stuff
716 s.defaultReadObject();
718 // Read in array length and allocate array
719 int arrayLength = s.readInt();
720 Object[] a = elementData = new Object[arrayLength];
722 // Read in all elements in the proper order.
723 for (int i=0; i<size; i++)
724 a[i] = s.readObject();
728 * Returns a list iterator over the elements in this list (in proper
729 * sequence), starting at the specified position in the list.
730 * The specified index indicates the first element that would be
731 * returned by an initial call to {@link ListIterator#next next}.
732 * An initial call to {@link ListIterator#previous previous} would
733 * return the element with the specified index minus one.
735 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
737 * @throws IndexOutOfBoundsException {@inheritDoc}
739 public ListIterator<E> listIterator(int index) {
740 if (index < 0 || index > size)
741 throw new IndexOutOfBoundsException("Index: "+index);
742 return new ListItr(index);
746 * Returns a list iterator over the elements in this list (in proper
749 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
751 * @see #listIterator(int)
753 public ListIterator<E> listIterator() {
754 return new ListItr(0);
758 * Returns an iterator over the elements in this list in proper sequence.
760 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
762 * @return an iterator over the elements in this list in proper sequence
764 public Iterator<E> iterator() {
769 * An optimized version of AbstractList.Itr
771 private class Itr implements Iterator<E> {
772 int cursor; // index of next element to return
773 int lastRet = -1; // index of last element returned; -1 if no such
774 int expectedModCount = modCount;
776 public boolean hasNext() {
777 return cursor != size;
780 @SuppressWarnings("unchecked")
782 checkForComodification();
785 throw new NoSuchElementException();
786 Object[] elementData = ArrayList.this.elementData;
787 if (i >= elementData.length)
788 throw new ConcurrentModificationException();
790 return (E) elementData[lastRet = i];
793 public void remove() {
795 throw new IllegalStateException();
796 checkForComodification();
799 ArrayList.this.remove(lastRet);
802 expectedModCount = modCount;
803 } catch (IndexOutOfBoundsException ex) {
804 throw new ConcurrentModificationException();
808 final void checkForComodification() {
809 if (modCount != expectedModCount)
810 throw new ConcurrentModificationException();
815 * An optimized version of AbstractList.ListItr
817 private class ListItr extends Itr implements ListIterator<E> {
823 public boolean hasPrevious() {
827 public int nextIndex() {
831 public int previousIndex() {
835 @SuppressWarnings("unchecked")
836 public E previous() {
837 checkForComodification();
840 throw new NoSuchElementException();
841 Object[] elementData = ArrayList.this.elementData;
842 if (i >= elementData.length)
843 throw new ConcurrentModificationException();
845 return (E) elementData[lastRet = i];
848 public void set(E e) {
850 throw new IllegalStateException();
851 checkForComodification();
854 ArrayList.this.set(lastRet, e);
855 } catch (IndexOutOfBoundsException ex) {
856 throw new ConcurrentModificationException();
860 public void add(E e) {
861 checkForComodification();
865 ArrayList.this.add(i, e);
868 expectedModCount = modCount;
869 } catch (IndexOutOfBoundsException ex) {
870 throw new ConcurrentModificationException();
876 * Returns a view of the portion of this list between the specified
877 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
878 * {@code fromIndex} and {@code toIndex} are equal, the returned list is
879 * empty.) The returned list is backed by this list, so non-structural
880 * changes in the returned list are reflected in this list, and vice-versa.
881 * The returned list supports all of the optional list operations.
883 * <p>This method eliminates the need for explicit range operations (of
884 * the sort that commonly exist for arrays). Any operation that expects
885 * a list can be used as a range operation by passing a subList view
886 * instead of a whole list. For example, the following idiom
887 * removes a range of elements from a list:
889 * list.subList(from, to).clear();
891 * Similar idioms may be constructed for {@link #indexOf(Object)} and
892 * {@link #lastIndexOf(Object)}, and all of the algorithms in the
893 * {@link Collections} class can be applied to a subList.
895 * <p>The semantics of the list returned by this method become undefined if
896 * the backing list (i.e., this list) is <i>structurally modified</i> in
897 * any way other than via the returned list. (Structural modifications are
898 * those that change the size of this list, or otherwise perturb it in such
899 * a fashion that iterations in progress may yield incorrect results.)
901 * @throws IndexOutOfBoundsException {@inheritDoc}
902 * @throws IllegalArgumentException {@inheritDoc}
904 public List<E> subList(int fromIndex, int toIndex) {
905 subListRangeCheck(fromIndex, toIndex, size);
906 return new SubList(this, 0, fromIndex, toIndex);
909 static void subListRangeCheck(int fromIndex, int toIndex, int size) {
911 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
913 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
914 if (fromIndex > toIndex)
915 throw new IllegalArgumentException("fromIndex(" + fromIndex +
916 ") > toIndex(" + toIndex + ")");
919 private class SubList extends AbstractList<E> implements RandomAccess {
920 private final AbstractList<E> parent;
921 private final int parentOffset;
922 private final int offset;
925 SubList(AbstractList<E> parent,
926 int offset, int fromIndex, int toIndex) {
927 this.parent = parent;
928 this.parentOffset = fromIndex;
929 this.offset = offset + fromIndex;
930 this.size = toIndex - fromIndex;
931 this.modCount = ArrayList.this.modCount;
934 public E set(int index, E e) {
936 checkForComodification();
937 E oldValue = ArrayList.this.elementData(offset + index);
938 ArrayList.this.elementData[offset + index] = e;
942 public E get(int index) {
944 checkForComodification();
945 return ArrayList.this.elementData(offset + index);
949 checkForComodification();
953 public void add(int index, E e) {
954 rangeCheckForAdd(index);
955 checkForComodification();
956 parent.add(parentOffset + index, e);
957 this.modCount = parent.modCount;
961 public E remove(int index) {
963 checkForComodification();
964 E result = parent.remove(parentOffset + index);
965 this.modCount = parent.modCount;
970 protected void removeRange(int fromIndex, int toIndex) {
971 checkForComodification();
972 parent.removeRange(parentOffset + fromIndex,
973 parentOffset + toIndex);
974 this.modCount = parent.modCount;
975 this.size -= toIndex - fromIndex;
978 public boolean addAll(Collection<? extends E> c) {
979 return addAll(this.size, c);
982 public boolean addAll(int index, Collection<? extends E> c) {
983 rangeCheckForAdd(index);
984 int cSize = c.size();
988 checkForComodification();
989 parent.addAll(parentOffset + index, c);
990 this.modCount = parent.modCount;
995 public Iterator<E> iterator() {
996 return listIterator();
999 public ListIterator<E> listIterator(final int index) {
1000 checkForComodification();
1001 rangeCheckForAdd(index);
1002 final int offset = this.offset;
1004 return new ListIterator<E>() {
1007 int expectedModCount = ArrayList.this.modCount;
1009 public boolean hasNext() {
1010 return cursor != SubList.this.size;
1013 @SuppressWarnings("unchecked")
1015 checkForComodification();
1017 if (i >= SubList.this.size)
1018 throw new NoSuchElementException();
1019 Object[] elementData = ArrayList.this.elementData;
1020 if (offset + i >= elementData.length)
1021 throw new ConcurrentModificationException();
1023 return (E) elementData[offset + (lastRet = i)];
1026 public boolean hasPrevious() {
1030 @SuppressWarnings("unchecked")
1031 public E previous() {
1032 checkForComodification();
1035 throw new NoSuchElementException();
1036 Object[] elementData = ArrayList.this.elementData;
1037 if (offset + i >= elementData.length)
1038 throw new ConcurrentModificationException();
1040 return (E) elementData[offset + (lastRet = i)];
1043 public int nextIndex() {
1047 public int previousIndex() {
1051 public void remove() {
1053 throw new IllegalStateException();
1054 checkForComodification();
1057 SubList.this.remove(lastRet);
1060 expectedModCount = ArrayList.this.modCount;
1061 } catch (IndexOutOfBoundsException ex) {
1062 throw new ConcurrentModificationException();
1066 public void set(E e) {
1068 throw new IllegalStateException();
1069 checkForComodification();
1072 ArrayList.this.set(offset + lastRet, e);
1073 } catch (IndexOutOfBoundsException ex) {
1074 throw new ConcurrentModificationException();
1078 public void add(E e) {
1079 checkForComodification();
1083 SubList.this.add(i, e);
1086 expectedModCount = ArrayList.this.modCount;
1087 } catch (IndexOutOfBoundsException ex) {
1088 throw new ConcurrentModificationException();
1092 final void checkForComodification() {
1093 if (expectedModCount != ArrayList.this.modCount)
1094 throw new ConcurrentModificationException();
1099 public List<E> subList(int fromIndex, int toIndex) {
1100 subListRangeCheck(fromIndex, toIndex, size);
1101 return new SubList(this, offset, fromIndex, toIndex);
1104 private void rangeCheck(int index) {
1105 if (index < 0 || index >= this.size)
1106 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1109 private void rangeCheckForAdd(int index) {
1110 if (index < 0 || index > this.size)
1111 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1114 private String outOfBoundsMsg(int index) {
1115 return "Index: "+index+", Size: "+this.size;
1118 private void checkForComodification() {
1119 if (ArrayList.this.modCount != this.modCount)
1120 throw new ConcurrentModificationException();