+ * This class is a member of the
+ *
* Java Collections Framework.
*
* @author Josh Bloch
* @author Neal Gafter
* @version %I%, %G%
- * @see Collection
- * @see List
- * @see LinkedList
- * @see Vector
+ * @see Collection
+ * @see List
+ * @see LinkedList
+ * @see Vector
* @since 1.2
*/
@@ -101,73 +121,52 @@ public class ArrayList extends Abstra
/**
* Constructs an empty list with the specified initial capacity.
*
- * @param initialCapacity the initial capacity of the list
- * @throws IllegalArgumentException if the specified initial capacity
- * is negative
+ * @param initialCapacity the initial capacity of the list
+ * @exception IllegalArgumentException if the specified initial capacity
+ * is negative
*/
public ArrayList(int initialCapacity) {
- super();
+ super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
- this.elementData = new Object[initialCapacity];
+ this.elementData = new Object[initialCapacity];
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
- this(10);
+ this(10);
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
- * iterator. The ArrayList instance has an initial capacity of
- * 110% the size of the specified collection.
+ * iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection extends E> c) {
- int size = c.size();
- // 10% for growth
- int cap = ((size/10)+1)*11;
- if (cap > 0) {
- Object[] a = new Object[cap];
- a[size] = a[size+1] = UNALLOCATED;
- Object[] b = c.toArray(a);
- if (b[size] == null && b[size+1] == UNALLOCATED) {
- b[size+1] = null;
- elementData = b;
- this.size = size;
- return;
- }
- }
- initFromConcurrentlyMutating(c);
- }
-
- private void initFromConcurrentlyMutating(Collection extends E> c) {
- elementData = c.toArray();
- size = elementData.length;
- // c.toArray might (incorrectly) not return Object[] (see 6260652)
- if (elementData.getClass() != Object[].class)
- elementData = Arrays.copyOf(elementData, size, Object[].class);
+ elementData = c.toArray();
+ size = elementData.length;
+ // c.toArray might (incorrectly) not return Object[] (see 6260652)
+ if (elementData.getClass() != Object[].class)
+ elementData = Arrays.copyOf(elementData, size, Object[].class);
}
- private final static Object UNALLOCATED = new Object();
-
/**
* Trims the capacity of this ArrayList instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an ArrayList instance.
*/
public void trimToSize() {
- modCount++;
- int oldCapacity = elementData.length;
- if (size < oldCapacity) {
+ modCount++;
+ int oldCapacity = elementData.length;
+ if (size < oldCapacity) {
elementData = Arrays.copyOf(elementData, size);
- }
+ }
}
/**
@@ -175,28 +174,19 @@ public class ArrayList extends Abstra
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
- * @param minCapacity the desired minimum capacity
+ * @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
- modCount++;
- if (minCapacity > elementData.length)
- growArray(minCapacity);
- }
-
- /**
- * Increases the capacity of the array.
- *
- * @param minCapacity the desired minimum capacity
- */
- private void growArray(int minCapacity) {
- int oldCapacity = elementData.length;
- // Double size if small; else grow by 50%
- int newCapacity = ((oldCapacity < 64)?
- (oldCapacity * 2):
- ((oldCapacity * 3)/2 + 1));
- if (newCapacity < minCapacity)
- newCapacity = minCapacity;
- elementData = Arrays.copyOf(elementData, newCapacity);
+ modCount++;
+ int oldCapacity = elementData.length;
+ if (minCapacity > oldCapacity) {
+ Object oldData[] = elementData;
+ int newCapacity = (oldCapacity * 3)/2 + 1;
+ if (newCapacity < minCapacity)
+ newCapacity = minCapacity;
+ // minCapacity is usually close to size, so this is a win:
+ elementData = Arrays.copyOf(elementData, newCapacity);
+ }
}
/**
@@ -205,7 +195,7 @@ public class ArrayList extends Abstra
* @return the number of elements in this list
*/
public int size() {
- return size;
+ return size;
}
/**
@@ -214,7 +204,7 @@ public class ArrayList extends Abstra
* @return true if this list contains no elements
*/
public boolean isEmpty() {
- return size == 0;
+ return size == 0;
}
/**
@@ -227,7 +217,7 @@ public class ArrayList extends Abstra
* @return true if this list contains the specified element
*/
public boolean contains(Object o) {
- return indexOf(o) >= 0;
+ return indexOf(o) >= 0;
}
/**
@@ -238,16 +228,16 @@ public class ArrayList extends Abstra
* or -1 if there is no such index.
*/
public int indexOf(Object o) {
- if (o == null) {
- for (int i = 0; i < size; i++)
- if (elementData[i]==null)
- return i;
- } else {
- for (int i = 0; i < size; i++)
- if (o.equals(elementData[i]))
- return i;
- }
- return -1;
+ if (o == null) {
+ for (int i = 0; i < size; i++)
+ if (elementData[i]==null)
+ return i;
+ } else {
+ for (int i = 0; i < size; i++)
+ if (o.equals(elementData[i]))
+ return i;
+ }
+ return -1;
}
/**
@@ -258,16 +248,16 @@ public class ArrayList extends Abstra
* or -1 if there is no such index.
*/
public int lastIndexOf(Object o) {
- if (o == null) {
- for (int i = size-1; i >= 0; i--)
- if (elementData[i]==null)
- return i;
- } else {
- for (int i = size-1; i >= 0; i--)
- if (o.equals(elementData[i]))
- return i;
- }
- return -1;
+ if (o == null) {
+ for (int i = size-1; i >= 0; i--)
+ if (elementData[i]==null)
+ return i;
+ } else {
+ for (int i = size-1; i >= 0; i--)
+ if (o.equals(elementData[i]))
+ return i;
+ }
+ return -1;
}
/**
@@ -277,15 +267,16 @@ public class ArrayList extends Abstra
* @return a clone of this ArrayList instance
*/
public Object clone() {
- try {
- ArrayList v = (ArrayList) super.clone();
- v.elementData = Arrays.copyOf(elementData, size);
- v.modCount = 0;
- return v;
- } catch (CloneNotSupportedException e) {
- // this shouldn't happen, since we are Cloneable
- throw new InternalError();
- }
+ try {
+ @SuppressWarnings("unchecked")
+ ArrayList v = (ArrayList) super.clone();
+ v.elementData = Arrays.copyOf(elementData, size);
+ v.modCount = 0;
+ return v;
+ } catch (CloneNotSupportedException e) {
+ // this shouldn't happen, since we are Cloneable
+ throw new InternalError();
+ }
}
/**
@@ -330,11 +321,12 @@ public class ArrayList extends Abstra
* this list
* @throws NullPointerException if the specified array is null
*/
+ @SuppressWarnings("unchecked")
public T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
- System.arraycopy(elementData, 0, a, 0, size);
+ System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
@@ -342,11 +334,9 @@ public class ArrayList extends Abstra
// Positional Access Operations
- /**
- * Creates and returns an appropriate exception for indexing errors.
- */
- private static IndexOutOfBoundsException rangeException(int i, int s) {
- return new IndexOutOfBoundsException("Index: " + i + ", Size: " + s);
+ @SuppressWarnings("unchecked")
+ E elementData(int index) {
+ return (E) elementData[index];
}
/**
@@ -357,9 +347,9 @@ public class ArrayList extends Abstra
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
- if (index >= size)
- throw rangeException(index, size);
- return (E)elementData[index];
+ rangeCheck(index);
+
+ return elementData(index);
}
/**
@@ -372,12 +362,11 @@ public class ArrayList extends Abstra
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
- if (index >= size)
- throw rangeException(index, size);
+ rangeCheck(index);
- E oldValue = (E) elementData[index];
- elementData[index] = element;
- return oldValue;
+ E oldValue = elementData(index);
+ elementData[index] = element;
+ return oldValue;
}
/**
@@ -387,12 +376,9 @@ public class ArrayList extends Abstra
* @return true (as specified by {@link Collection#add})
*/
public boolean add(E e) {
- ++modCount;
- int s = size++;
- if (s >= elementData.length)
- growArray(s + 1);
- elementData[s] = e;
- return true;
+ ensureCapacity(size + 1); // Increments modCount!!
+ elementData[size++] = e;
+ return true;
}
/**
@@ -405,16 +391,13 @@ public class ArrayList extends Abstra
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
- int s = size;
- if (index > s || index < 0)
- throw rangeException(index, s);
- ++modCount;
- size = s + 1;
- if (s >= elementData.length)
- growArray(s + 1);
- System.arraycopy(elementData, index, elementData, index + 1,
- s - index);
- elementData[index] = element;
+ rangeCheckForAdd(index);
+
+ ensureCapacity(size+1); // Increments modCount!!
+ System.arraycopy(elementData, index, elementData, index + 1,
+ size - index);
+ elementData[index] = element;
+ size++;
}
/**
@@ -427,18 +410,18 @@ public class ArrayList extends Abstra
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
- int s = size - 1;
- if (index > s)
- throw rangeException(index, size);
- size = s;
- modCount++;
- Object oldValue = elementData[index];
- int numMoved = s - index;
- if (numMoved > 0)
- System.arraycopy(elementData, index+1, elementData, index,
+ rangeCheck(index);
+
+ modCount++;
+ E oldValue = elementData(index);
+
+ int numMoved = size - index - 1;
+ if (numMoved > 0)
+ System.arraycopy(elementData, index+1, elementData, index,
numMoved);
- elementData[s] = null; // forget removed element
- return (E)oldValue;
+ elementData[--size] = null; // Let gc do its work
+
+ return oldValue;
}
/**
@@ -455,20 +438,20 @@ public class ArrayList extends Abstra
* @return true if this list contained the specified element
*/
public boolean remove(Object o) {
- if (o == null) {
+ if (o == null) {
for (int index = 0; index < size; index++)
- if (elementData[index] == null) {
- fastRemove(index);
- return true;
- }
- } else {
- for (int index = 0; index < size; index++)
- if (o.equals(elementData[index])) {
- fastRemove(index);
- return true;
- }
+ if (elementData[index] == null) {
+ fastRemove(index);
+ return true;
+ }
+ } else {
+ for (int index = 0; index < size; index++)
+ if (o.equals(elementData[index])) {
+ fastRemove(index);
+ return true;
+ }
}
- return false;
+ return false;
}
/*
@@ -489,13 +472,13 @@ public class ArrayList extends Abstra
* be empty after this call returns.
*/
public void clear() {
- modCount++;
+ modCount++;
- // Let gc do its work
- for (int i = 0; i < size; i++)
- elementData[i] = null;
+ // Let gc do its work
+ for (int i = 0; i < size; i++)
+ elementData[i] = null;
- size = 0;
+ size = 0;
}
/**
@@ -512,12 +495,12 @@ public class ArrayList extends Abstra
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection extends E> c) {
- Object[] a = c.toArray();
+ Object[] a = c.toArray();
int numNew = a.length;
- ensureCapacity(size + numNew); // Increments modCount
+ ensureCapacity(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
- return numNew != 0;
+ return numNew != 0;
}
/**
@@ -536,47 +519,137 @@ public class ArrayList extends Abstra
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection extends E> c) {
- if (index > size || index < 0)
- throw new IndexOutOfBoundsException(
- "Index: " + index + ", Size: " + size);
-
- Object[] a = c.toArray();
- int numNew = a.length;
- ensureCapacity(size + numNew); // Increments modCount
-
- int numMoved = size - index;
- if (numMoved > 0)
- System.arraycopy(elementData, index, elementData, index + numNew,
- numMoved);
+ rangeCheckForAdd(index);
+
+ Object[] a = c.toArray();
+ int numNew = a.length;
+ ensureCapacity(size + numNew); // Increments modCount
+
+ int numMoved = size - index;
+ if (numMoved > 0)
+ System.arraycopy(elementData, index, elementData, index + numNew,
+ numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
- size += numNew;
- return numNew != 0;
+ size += numNew;
+ return numNew != 0;
}
/**
* Removes from this list all of the elements whose index is between
- * fromIndex, inclusive, and toIndex, exclusive.
+ * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
* Shifts any succeeding elements to the left (reduces their index).
- * This call shortens the list by (toIndex - fromIndex) elements.
- * (If toIndex==fromIndex, this operation has no effect.)
+ * This call shortens the list by {@code (toIndex - fromIndex)} elements.
+ * (If {@code toIndex==fromIndex}, this operation has no effect.)
*
- * @param fromIndex index of first element to be removed
- * @param toIndex index after last element to be removed
- * @throws IndexOutOfBoundsException if fromIndex or toIndex out of
- * range (fromIndex < 0 || fromIndex >= size() || toIndex
- * > size() || toIndex < fromIndex)
+ * @throws IndexOutOfBoundsException if {@code fromIndex} or
+ * {@code toIndex} is out of range
+ * ({@code fromIndex < 0 ||
+ * fromIndex >= size() ||
+ * toIndex > size() ||
+ * toIndex < fromIndex})
*/
protected void removeRange(int fromIndex, int toIndex) {
- modCount++;
- int numMoved = size - toIndex;
+ modCount++;
+ int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
- // Let gc do its work
- int newSize = size - (toIndex-fromIndex);
- while (size != newSize)
- elementData[--size] = null;
+ // Let gc do its work
+ int newSize = size - (toIndex-fromIndex);
+ while (size != newSize)
+ elementData[--size] = null;
+ }
+
+ /**
+ * Checks if the given index is in range. If not, throws an appropriate
+ * runtime exception. This method does *not* check if the index is
+ * negative: It is always used immediately prior to an array access,
+ * which throws an ArrayIndexOutOfBoundsException if index is negative.
+ */
+ private void rangeCheck(int index) {
+ if (index >= size)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ /**
+ * A version of rangeCheck used by add and addAll.
+ */
+ private void rangeCheckForAdd(int index) {
+ if (index > size || index < 0)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ /**
+ * Constructs an IndexOutOfBoundsException detail message.
+ * Of the many possible refactorings of the error handling code,
+ * this "outlining" performs best with both server and client VMs.
+ */
+ private String outOfBoundsMsg(int index) {
+ return "Index: "+index+", Size: "+size;
+ }
+
+ /**
+ * Removes from this list all of its elements that are contained in the
+ * specified collection.
+ *
+ * @param c collection containing elements to be removed from this list
+ * @return {@code true} if this list changed as a result of the call
+ * @throws ClassCastException if the class of an element of this list
+ * is incompatible with the specified collection (optional)
+ * @throws NullPointerException if this list contains a null element and the
+ * specified collection does not permit null elements (optional),
+ * or if the specified collection is null
+ * @see Collection#contains(Object)
+ */
+ public boolean removeAll(Collection> c) {
+ return batchRemove(c, false);
+ }
+
+ /**
+ * Retains only the elements in this list that are contained in the
+ * specified collection. In other words, removes from this list all
+ * of its elements that are not contained in the specified collection.
+ *
+ * @param c collection containing elements to be retained in this list
+ * @return {@code true} if this list changed as a result of the call
+ * @throws ClassCastException if the class of an element of this list
+ * is incompatible with the specified collection (optional)
+ * @throws NullPointerException if this list contains a null element and the
+ * specified collection does not permit null elements (optional),
+ * or if the specified collection is null
+ * @see Collection#contains(Object)
+ */
+ public boolean retainAll(Collection> c) {
+ return batchRemove(c, true);
+ }
+
+ private boolean batchRemove(Collection> c, boolean complement) {
+ final Object[] elementData = this.elementData;
+ int r = 0, w = 0;
+ boolean modified = false;
+ try {
+ for (; r < size; r++)
+ if (c.contains(elementData[r]) == complement)
+ elementData[w++] = elementData[r];
+ } finally {
+ // Preserve behavioral compatibility with AbstractCollection,
+ // even if c.contains() throws.
+ if (r != size) {
+ System.arraycopy(elementData, r,
+ elementData, w,
+ size - r);
+ w += size - r;
+ }
+ if (w != size) {
+ for (int i = w; i < size; i++)
+ elementData[i] = null;
+ modCount += size - w;
+ size = w;
+ modified = true;
+ }
+ }
+ return modified;
}
/**
@@ -589,18 +662,18 @@ public class ArrayList extends Abstra
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
- // Write out element count, and any hidden stuff
- int expectedModCount = modCount;
- s.defaultWriteObject();
+ // Write out element count, and any hidden stuff
+ int expectedModCount = modCount;
+ s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);
- // Write out all elements in the proper order.
- for (int i=0; i extends Abstra
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
- // Read in size, and any hidden stuff
- s.defaultReadObject();
+ // Read in size, and any hidden stuff
+ s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
Object[] a = elementData = new Object[arrayLength];
- // Read in all elements in the proper order.
- for (int i=0; iList.listIterator(int).
+ * The specified index indicates the first element that would be
+ * returned by an initial call to {@link ListIterator#next next}.
+ * An initial call to {@link ListIterator#previous previous} would
+ * return the element with the specified index minus one.
+ *
+ *
The returned list iterator is fail-fast.
*
- * The list-iterator is fail-fast: if the list is structurally
- * modified at any time after the Iterator is created, in any way except
- * through the list-iterator's own remove or add
- * methods, the list-iterator will throw a
- * ConcurrentModificationException. Thus, in the face of
- * concurrent modification, the iterator fails quickly and cleanly, rather
- * than risking arbitrary, non-deterministic behavior at an undetermined
- * time in the future.
- *
- * @param index index of the first element to be returned from the
- * list-iterator (by a call to next)
- * @return a ListIterator of the elements in this list (in proper
- * sequence), starting at the specified position in the list
* @throws IndexOutOfBoundsException {@inheritDoc}
- * @see List#listIterator(int)
*/
public ListIterator listIterator(int index) {
- if (index < 0 || index > size)
+ if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
- return new ArrayListIterator(index);
+ return new ListItr(index);
+ }
+
+ /**
+ * Returns a list iterator over the elements in this list (in proper
+ * sequence).
+ *
+ * The returned list iterator is fail-fast.
+ *
+ * @see #listIterator(int)
+ */
+ public ListIterator listIterator() {
+ return new ListItr(0);
}
/**
* Returns an iterator over the elements in this list in proper sequence.
*
+ * The returned iterator is fail-fast.
+ *
* @return an iterator over the elements in this list in proper sequence
*/
public Iterator iterator() {
- return new ArrayListIterator(0);
+ return new Itr();
}
/**
- * A streamlined version of AbstractList.Itr
+ * An optimized version of AbstractList.Itr
*/
- final class ArrayListIterator implements ListIterator {
- int cursor; // index of next element to return;
- int lastRet; // index of last element, or -1 if no such
- int expectedModCount; // to check for CME
+ private class Itr implements Iterator {
+ int cursor; // index of next element to return
+ int lastRet = -1; // index of last element returned; -1 if no such
+ int expectedModCount = modCount;
- ArrayListIterator(int index) {
- cursor = index;
- lastRet = -1;
- expectedModCount = modCount;
- }
+ public boolean hasNext() {
+ return cursor != size;
+ }
- public boolean hasNext() {
- return cursor < size;
- }
+ @SuppressWarnings("unchecked")
+ public E next() {
+ checkForComodification();
+ int i = cursor;
+ if (i >= size)
+ throw new NoSuchElementException();
+ Object[] elementData = ArrayList.this.elementData;
+ if (i >= elementData.length)
+ throw new ConcurrentModificationException();
+ cursor = i + 1;
+ return (E) elementData[lastRet = i];
+ }
- public boolean hasPrevious() {
- return cursor > 0;
- }
+ public void remove() {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
+ try {
+ ArrayList.this.remove(lastRet);
+ cursor = lastRet;
+ lastRet = -1;
+ expectedModCount = modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
- public int nextIndex() {
- return cursor;
- }
+ final void checkForComodification() {
+ if (modCount != expectedModCount)
+ throw new ConcurrentModificationException();
+ }
+ }
- public int previousIndex() {
- return cursor - 1;
- }
+ /**
+ * An optimized version of AbstractList.ListItr
+ */
+ private class ListItr extends Itr implements ListIterator {
+ ListItr(int index) {
+ super();
+ cursor = index;
+ }
- public E next() {
- if (expectedModCount == modCount) {
+ public boolean hasPrevious() {
+ return cursor != 0;
+ }
+
+ public int nextIndex() {
+ return cursor;
+ }
+
+ public int previousIndex() {
+ return cursor - 1;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E previous() {
+ checkForComodification();
+ int i = cursor - 1;
+ if (i < 0)
+ throw new NoSuchElementException();
+ Object[] elementData = ArrayList.this.elementData;
+ if (i >= elementData.length)
+ throw new ConcurrentModificationException();
+ cursor = i;
+ return (E) elementData[lastRet = i];
+ }
+
+ public void set(E e) {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
+ try {
+ ArrayList.this.set(lastRet, e);
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ public void add(E e) {
+ checkForComodification();
+
+ try {
int i = cursor;
- if (i < size) {
+ ArrayList.this.add(i, e);
+ cursor = i + 1;
+ lastRet = -1;
+ expectedModCount = modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+ }
+
+ /**
+ * Returns a view of the portion of this list between the specified
+ * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
+ * {@code fromIndex} and {@code toIndex} are equal, the returned list is
+ * empty.) The returned list is backed by this list, so non-structural
+ * changes in the returned list are reflected in this list, and vice-versa.
+ * The returned list supports all of the optional list operations.
+ *
+ * This method eliminates the need for explicit range operations (of
+ * the sort that commonly exist for arrays). Any operation that expects
+ * a list can be used as a range operation by passing a subList view
+ * instead of a whole list. For example, the following idiom
+ * removes a range of elements from a list:
+ *
+ * list.subList(from, to).clear();
+ *
+ * Similar idioms may be constructed for {@link #indexOf(Object)} and
+ * {@link #lastIndexOf(Object)}, and all of the algorithms in the
+ * {@link Collections} class can be applied to a subList.
+ *
+ * The semantics of the list returned by this method become undefined if
+ * the backing list (i.e., this list) is structurally modified in
+ * any way other than via the returned list. (Structural modifications are
+ * those that change the size of this list, or otherwise perturb it in such
+ * a fashion that iterations in progress may yield incorrect results.)
+ *
+ * @throws IndexOutOfBoundsException {@inheritDoc}
+ * @throws IllegalArgumentException {@inheritDoc}
+ */
+ public List subList(int fromIndex, int toIndex) {
+ subListRangeCheck(fromIndex, toIndex, size);
+ return new SubList(this, 0, fromIndex, toIndex);
+ }
+
+ static void subListRangeCheck(int fromIndex, int toIndex, int size) {
+ if (fromIndex < 0)
+ throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
+ if (toIndex > size)
+ throw new IndexOutOfBoundsException("toIndex = " + toIndex);
+ if (fromIndex > toIndex)
+ throw new IllegalArgumentException("fromIndex(" + fromIndex +
+ ") > toIndex(" + toIndex + ")");
+ }
+
+ private class SubList extends AbstractList implements RandomAccess {
+ private final AbstractList parent;
+ private final int parentOffset;
+ private final int offset;
+ private int size;
+
+ SubList(AbstractList parent,
+ int offset, int fromIndex, int toIndex) {
+ this.parent = parent;
+ this.parentOffset = fromIndex;
+ this.offset = offset + fromIndex;
+ this.size = toIndex - fromIndex;
+ this.modCount = ArrayList.this.modCount;
+ }
+
+ public E set(int index, E e) {
+ rangeCheck(index);
+ checkForComodification();
+ E oldValue = ArrayList.this.elementData(offset + index);
+ ArrayList.this.elementData[offset + index] = e;
+ return oldValue;
+ }
+
+ public E get(int index) {
+ rangeCheck(index);
+ checkForComodification();
+ return ArrayList.this.elementData(offset + index);
+ }
+
+ public int size() {
+ checkForComodification();
+ return this.size;
+ }
+
+ public void add(int index, E e) {
+ rangeCheckForAdd(index);
+ checkForComodification();
+ parent.add(parentOffset + index, e);
+ this.modCount = parent.modCount;
+ this.size++;
+ }
+
+ public E remove(int index) {
+ rangeCheck(index);
+ checkForComodification();
+ E result = parent.remove(parentOffset + index);
+ this.modCount = parent.modCount;
+ this.size--;
+ return result;
+ }
+
+ protected void removeRange(int fromIndex, int toIndex) {
+ checkForComodification();
+ parent.removeRange(parentOffset + fromIndex,
+ parentOffset + toIndex);
+ this.modCount = parent.modCount;
+ this.size -= toIndex - fromIndex;
+ }
+
+ public boolean addAll(Collection extends E> c) {
+ return addAll(this.size, c);
+ }
+
+ public boolean addAll(int index, Collection extends E> c) {
+ rangeCheckForAdd(index);
+ int cSize = c.size();
+ if (cSize==0)
+ return false;
+
+ checkForComodification();
+ parent.addAll(parentOffset + index, c);
+ this.modCount = parent.modCount;
+ this.size += cSize;
+ return true;
+ }
+
+ public Iterator iterator() {
+ return listIterator();
+ }
+
+ public ListIterator listIterator(final int index) {
+ checkForComodification();
+ rangeCheckForAdd(index);
+
+ return new ListIterator() {
+ int cursor = index;
+ int lastRet = -1;
+ int expectedModCount = ArrayList.this.modCount;
+
+ public boolean hasNext() {
+ return cursor != SubList.this.size;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E next() {
+ checkForComodification();
+ int i = cursor;
+ if (i >= SubList.this.size)
+ throw new NoSuchElementException();
+ Object[] elementData = ArrayList.this.elementData;
+ if (offset + i >= elementData.length)
+ throw new ConcurrentModificationException();
+ cursor = i + 1;
+ return (E) elementData[offset + (lastRet = i)];
+ }
+
+ public boolean hasPrevious() {
+ return cursor != 0;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E previous() {
+ checkForComodification();
+ int i = cursor - 1;
+ if (i < 0)
+ throw new NoSuchElementException();
+ Object[] elementData = ArrayList.this.elementData;
+ if (offset + i >= elementData.length)
+ throw new ConcurrentModificationException();
+ cursor = i;
+ return (E) elementData[offset + (lastRet = i)];
+ }
+
+ public int nextIndex() {
+ return cursor;
+ }
+
+ public int previousIndex() {
+ return cursor - 1;
+ }
+
+ public void remove() {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
try {
- E e = (E)elementData[i];
- lastRet = i;
- cursor = i + 1;
- return e;
- } catch (IndexOutOfBoundsException fallthrough) {
+ SubList.this.remove(lastRet);
+ cursor = lastRet;
+ lastRet = -1;
+ expectedModCount = ArrayList.this.modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
}
}
- }
- // Prefer reporting CME if applicable on failures
- if (expectedModCount == modCount)
- throw new NoSuchElementException();
- throw new ConcurrentModificationException();
- }
- public E previous() {
- if (expectedModCount == modCount) {
- int i = cursor - 1;
- if (i < size) {
+ public void set(E e) {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ checkForComodification();
+
try {
- E e = (E)elementData[i];
- lastRet = i;
- cursor = i;
- return e;
- } catch (IndexOutOfBoundsException fallthrough) {
+ ArrayList.this.set(offset + lastRet, e);
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
}
}
- }
- if (expectedModCount == modCount)
- throw new NoSuchElementException();
- throw new ConcurrentModificationException();
+
+ public void add(E e) {
+ checkForComodification();
+
+ try {
+ int i = cursor;
+ SubList.this.add(i, e);
+ cursor = i + 1;
+ lastRet = -1;
+ expectedModCount = ArrayList.this.modCount;
+ } catch (IndexOutOfBoundsException ex) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ final void checkForComodification() {
+ if (expectedModCount != ArrayList.this.modCount)
+ throw new ConcurrentModificationException();
+ }
+ };
}
- public void remove() {
- if (lastRet < 0)
- throw new IllegalStateException();
- if (modCount != expectedModCount)
- throw new ConcurrentModificationException();
- ArrayList.this.remove(lastRet);
- if (lastRet < cursor)
- cursor--;
- lastRet = -1;
- expectedModCount = modCount;
- }
-
- public void set(E e) {
- if (lastRet < 0)
- throw new IllegalStateException();
- if (modCount != expectedModCount)
- throw new ConcurrentModificationException();
- ArrayList.this.set(lastRet, e);
- expectedModCount = modCount;
- }
+ public List subList(int fromIndex, int toIndex) {
+ subListRangeCheck(fromIndex, toIndex, size);
+ return new SubList(this, offset, fromIndex, toIndex);
+ }
- public void add(E e) {
- if (modCount != expectedModCount)
+ private void rangeCheck(int index) {
+ if (index < 0 || index >= this.size)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ private void rangeCheckForAdd(int index) {
+ if (index < 0 || index > this.size)
+ throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
+ }
+
+ private String outOfBoundsMsg(int index) {
+ return "Index: "+index+", Size: "+this.size;
+ }
+
+ private void checkForComodification() {
+ if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
- ArrayList.this.add(cursor++, e);
- lastRet = -1;
- expectedModCount = modCount;
- }
+ }
}
-
}