jaroslav@557: /* jaroslav@557: * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. jaroslav@557: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@557: * jaroslav@557: * This code is free software; you can redistribute it and/or modify it jaroslav@557: * under the terms of the GNU General Public License version 2 only, as jaroslav@557: * published by the Free Software Foundation. Oracle designates this jaroslav@557: * particular file as subject to the "Classpath" exception as provided jaroslav@557: * by Oracle in the LICENSE file that accompanied this code. jaroslav@557: * jaroslav@557: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@557: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@557: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@557: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@557: * accompanied this code). jaroslav@557: * jaroslav@557: * You should have received a copy of the GNU General Public License version jaroslav@557: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@557: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@557: * jaroslav@557: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@557: * or visit www.oracle.com if you need additional information or have any jaroslav@557: * questions. jaroslav@557: */ jaroslav@557: jaroslav@557: package java.util; jaroslav@557: jaroslav@560: jaroslav@557: /** jaroslav@557: * Resizable-array implementation of the List interface. Implements jaroslav@557: * all optional list operations, and permits all elements, including jaroslav@557: * null. In addition to implementing the List interface, jaroslav@557: * this class provides methods to manipulate the size of the array that is jaroslav@557: * used internally to store the list. (This class is roughly equivalent to jaroslav@557: * Vector, except that it is unsynchronized.) jaroslav@557: * jaroslav@557: *

The size, isEmpty, get, set, jaroslav@557: * iterator, and listIterator operations run in constant jaroslav@557: * time. The add operation runs in amortized constant time, jaroslav@557: * that is, adding n elements requires O(n) time. All of the other operations jaroslav@557: * run in linear time (roughly speaking). The constant factor is low compared jaroslav@557: * to that for the LinkedList implementation. jaroslav@557: * jaroslav@557: *

Each ArrayList instance has a capacity. The capacity is jaroslav@557: * the size of the array used to store the elements in the list. It is always jaroslav@557: * at least as large as the list size. As elements are added to an ArrayList, jaroslav@557: * its capacity grows automatically. The details of the growth policy are not jaroslav@557: * specified beyond the fact that adding an element has constant amortized jaroslav@557: * time cost. jaroslav@557: * jaroslav@557: *

An application can increase the capacity of an ArrayList instance jaroslav@557: * before adding a large number of elements using the ensureCapacity jaroslav@557: * operation. This may reduce the amount of incremental reallocation. jaroslav@557: * jaroslav@557: *

Note that this implementation is not synchronized. jaroslav@557: * If multiple threads access an ArrayList instance concurrently, jaroslav@557: * and at least one of the threads modifies the list structurally, it jaroslav@557: * must be synchronized externally. (A structural modification is jaroslav@557: * any operation that adds or deletes one or more elements, or explicitly jaroslav@557: * resizes the backing array; merely setting the value of an element is not jaroslav@557: * a structural modification.) This is typically accomplished by jaroslav@557: * synchronizing on some object that naturally encapsulates the list. jaroslav@557: * jaroslav@557: * If no such object exists, the list should be "wrapped" using the jaroslav@557: * {@link Collections#synchronizedList Collections.synchronizedList} jaroslav@557: * method. This is best done at creation time, to prevent accidental jaroslav@557: * unsynchronized access to the list:

jaroslav@557:  *   List list = Collections.synchronizedList(new ArrayList(...));
jaroslav@557: * jaroslav@557: *

jaroslav@557: * The iterators returned by this class's {@link #iterator() iterator} and jaroslav@557: * {@link #listIterator(int) listIterator} methods are fail-fast: jaroslav@557: * if the list is structurally modified at any time after the iterator is jaroslav@557: * created, in any way except through the iterator's own jaroslav@557: * {@link ListIterator#remove() remove} or jaroslav@557: * {@link ListIterator#add(Object) add} methods, the iterator will throw a jaroslav@557: * {@link ConcurrentModificationException}. Thus, in the face of jaroslav@557: * concurrent modification, the iterator fails quickly and cleanly, rather jaroslav@557: * than risking arbitrary, non-deterministic behavior at an undetermined jaroslav@557: * time in the future. jaroslav@557: * jaroslav@557: *

Note that the fail-fast behavior of an iterator cannot be guaranteed jaroslav@557: * as it is, generally speaking, impossible to make any hard guarantees in the jaroslav@557: * presence of unsynchronized concurrent modification. Fail-fast iterators jaroslav@557: * throw {@code ConcurrentModificationException} on a best-effort basis. jaroslav@557: * Therefore, it would be wrong to write a program that depended on this jaroslav@557: * exception for its correctness: the fail-fast behavior of iterators jaroslav@557: * should be used only to detect bugs. jaroslav@557: * jaroslav@557: *

This class is a member of the jaroslav@557: * jaroslav@557: * Java Collections Framework. jaroslav@557: * jaroslav@557: * @author Josh Bloch jaroslav@557: * @author Neal Gafter jaroslav@557: * @see Collection jaroslav@557: * @see List jaroslav@557: * @see LinkedList jaroslav@557: * @see Vector jaroslav@557: * @since 1.2 jaroslav@557: */ jaroslav@557: jaroslav@557: public class ArrayList extends AbstractList jaroslav@557: implements List, RandomAccess, Cloneable, java.io.Serializable jaroslav@557: { jaroslav@557: private static final long serialVersionUID = 8683452581122892189L; jaroslav@557: jaroslav@557: /** jaroslav@557: * The array buffer into which the elements of the ArrayList are stored. jaroslav@557: * The capacity of the ArrayList is the length of this array buffer. jaroslav@557: */ jaroslav@557: private transient Object[] elementData; jaroslav@557: jaroslav@557: /** jaroslav@557: * The size of the ArrayList (the number of elements it contains). jaroslav@557: * jaroslav@557: * @serial jaroslav@557: */ jaroslav@557: private int size; jaroslav@557: jaroslav@557: /** jaroslav@557: * Constructs an empty list with the specified initial capacity. jaroslav@557: * jaroslav@557: * @param initialCapacity the initial capacity of the list jaroslav@557: * @throws IllegalArgumentException if the specified initial capacity jaroslav@557: * is negative jaroslav@557: */ jaroslav@557: public ArrayList(int initialCapacity) { jaroslav@557: super(); jaroslav@557: if (initialCapacity < 0) jaroslav@557: throw new IllegalArgumentException("Illegal Capacity: "+ jaroslav@557: initialCapacity); jaroslav@557: this.elementData = new Object[initialCapacity]; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Constructs an empty list with an initial capacity of ten. jaroslav@557: */ jaroslav@557: public ArrayList() { jaroslav@557: this(10); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Constructs a list containing the elements of the specified jaroslav@557: * collection, in the order they are returned by the collection's jaroslav@557: * iterator. jaroslav@557: * jaroslav@557: * @param c the collection whose elements are to be placed into this list jaroslav@557: * @throws NullPointerException if the specified collection is null jaroslav@557: */ jaroslav@557: public ArrayList(Collection c) { jaroslav@557: elementData = c.toArray(); jaroslav@557: size = elementData.length; jaroslav@557: // c.toArray might (incorrectly) not return Object[] (see 6260652) jaroslav@557: if (elementData.getClass() != Object[].class) jaroslav@557: elementData = Arrays.copyOf(elementData, size, Object[].class); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Trims the capacity of this ArrayList instance to be the jaroslav@557: * list's current size. An application can use this operation to minimize jaroslav@557: * the storage of an ArrayList instance. jaroslav@557: */ jaroslav@557: public void trimToSize() { jaroslav@557: modCount++; jaroslav@557: int oldCapacity = elementData.length; jaroslav@557: if (size < oldCapacity) { jaroslav@557: elementData = Arrays.copyOf(elementData, size); jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Increases the capacity of this ArrayList instance, if jaroslav@557: * necessary, to ensure that it can hold at least the number of elements jaroslav@557: * specified by the minimum capacity argument. jaroslav@557: * jaroslav@557: * @param minCapacity the desired minimum capacity jaroslav@557: */ jaroslav@557: public void ensureCapacity(int minCapacity) { jaroslav@557: if (minCapacity > 0) jaroslav@557: ensureCapacityInternal(minCapacity); jaroslav@557: } jaroslav@557: jaroslav@557: private void ensureCapacityInternal(int minCapacity) { jaroslav@557: modCount++; jaroslav@557: // overflow-conscious code jaroslav@557: if (minCapacity - elementData.length > 0) jaroslav@557: grow(minCapacity); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * The maximum size of array to allocate. jaroslav@557: * Some VMs reserve some header words in an array. jaroslav@557: * Attempts to allocate larger arrays may result in jaroslav@557: * OutOfMemoryError: Requested array size exceeds VM limit jaroslav@557: */ jaroslav@557: private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; jaroslav@557: jaroslav@557: /** jaroslav@557: * Increases the capacity to ensure that it can hold at least the jaroslav@557: * number of elements specified by the minimum capacity argument. jaroslav@557: * jaroslav@557: * @param minCapacity the desired minimum capacity jaroslav@557: */ jaroslav@557: private void grow(int minCapacity) { jaroslav@557: // overflow-conscious code jaroslav@557: int oldCapacity = elementData.length; jaroslav@557: int newCapacity = oldCapacity + (oldCapacity >> 1); jaroslav@557: if (newCapacity - minCapacity < 0) jaroslav@557: newCapacity = minCapacity; jaroslav@557: if (newCapacity - MAX_ARRAY_SIZE > 0) jaroslav@557: newCapacity = hugeCapacity(minCapacity); jaroslav@557: // minCapacity is usually close to size, so this is a win: jaroslav@557: elementData = Arrays.copyOf(elementData, newCapacity); jaroslav@557: } jaroslav@557: jaroslav@557: private static int hugeCapacity(int minCapacity) { jaroslav@557: if (minCapacity < 0) // overflow jaroslav@557: throw new OutOfMemoryError(); jaroslav@557: return (minCapacity > MAX_ARRAY_SIZE) ? jaroslav@557: Integer.MAX_VALUE : jaroslav@557: MAX_ARRAY_SIZE; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns the number of elements in this list. jaroslav@557: * jaroslav@557: * @return the number of elements in this list jaroslav@557: */ jaroslav@557: public int size() { jaroslav@557: return size; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns true if this list contains no elements. jaroslav@557: * jaroslav@557: * @return true if this list contains no elements jaroslav@557: */ jaroslav@557: public boolean isEmpty() { jaroslav@557: return size == 0; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns true if this list contains the specified element. jaroslav@557: * More formally, returns true if and only if this list contains jaroslav@557: * at least one element e such that jaroslav@557: * (o==null ? e==null : o.equals(e)). jaroslav@557: * jaroslav@557: * @param o element whose presence in this list is to be tested jaroslav@557: * @return true if this list contains the specified element jaroslav@557: */ jaroslav@557: public boolean contains(Object o) { jaroslav@557: return indexOf(o) >= 0; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns the index of the first occurrence of the specified element jaroslav@557: * in this list, or -1 if this list does not contain the element. jaroslav@557: * More formally, returns the lowest index i such that jaroslav@557: * (o==null ? get(i)==null : o.equals(get(i))), jaroslav@557: * or -1 if there is no such index. jaroslav@557: */ jaroslav@557: public int indexOf(Object o) { jaroslav@557: if (o == null) { jaroslav@557: for (int i = 0; i < size; i++) jaroslav@557: if (elementData[i]==null) jaroslav@557: return i; jaroslav@557: } else { jaroslav@557: for (int i = 0; i < size; i++) jaroslav@557: if (o.equals(elementData[i])) jaroslav@557: return i; jaroslav@557: } jaroslav@557: return -1; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns the index of the last occurrence of the specified element jaroslav@557: * in this list, or -1 if this list does not contain the element. jaroslav@557: * More formally, returns the highest index i such that jaroslav@557: * (o==null ? get(i)==null : o.equals(get(i))), jaroslav@557: * or -1 if there is no such index. jaroslav@557: */ jaroslav@557: public int lastIndexOf(Object o) { jaroslav@557: if (o == null) { jaroslav@557: for (int i = size-1; i >= 0; i--) jaroslav@557: if (elementData[i]==null) jaroslav@557: return i; jaroslav@557: } else { jaroslav@557: for (int i = size-1; i >= 0; i--) jaroslav@557: if (o.equals(elementData[i])) jaroslav@557: return i; jaroslav@557: } jaroslav@557: return -1; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns a shallow copy of this ArrayList instance. (The jaroslav@557: * elements themselves are not copied.) jaroslav@557: * jaroslav@557: * @return a clone of this ArrayList instance jaroslav@557: */ jaroslav@557: public Object clone() { jaroslav@557: try { jaroslav@557: @SuppressWarnings("unchecked") jaroslav@557: ArrayList v = (ArrayList) super.clone(); jaroslav@557: v.elementData = Arrays.copyOf(elementData, size); jaroslav@557: v.modCount = 0; jaroslav@557: return v; jaroslav@557: } catch (CloneNotSupportedException e) { jaroslav@557: // this shouldn't happen, since we are Cloneable jaroslav@557: throw new InternalError(); jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns an array containing all of the elements in this list jaroslav@557: * in proper sequence (from first to last element). jaroslav@557: * jaroslav@557: *

The returned array will be "safe" in that no references to it are jaroslav@557: * maintained by this list. (In other words, this method must allocate jaroslav@557: * a new array). The caller is thus free to modify the returned array. jaroslav@557: * jaroslav@557: *

This method acts as bridge between array-based and collection-based jaroslav@557: * APIs. jaroslav@557: * jaroslav@557: * @return an array containing all of the elements in this list in jaroslav@557: * proper sequence jaroslav@557: */ jaroslav@557: public Object[] toArray() { jaroslav@557: return Arrays.copyOf(elementData, size); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns an array containing all of the elements in this list in proper jaroslav@557: * sequence (from first to last element); the runtime type of the returned jaroslav@557: * array is that of the specified array. If the list fits in the jaroslav@557: * specified array, it is returned therein. Otherwise, a new array is jaroslav@557: * allocated with the runtime type of the specified array and the size of jaroslav@557: * this list. jaroslav@557: * jaroslav@557: *

If the list fits in the specified array with room to spare jaroslav@557: * (i.e., the array has more elements than the list), the element in jaroslav@557: * the array immediately following the end of the collection is set to jaroslav@557: * null. (This is useful in determining the length of the jaroslav@557: * list only if the caller knows that the list does not contain jaroslav@557: * any null elements.) jaroslav@557: * jaroslav@557: * @param a the array into which the elements of the list are to jaroslav@557: * be stored, if it is big enough; otherwise, a new array of the jaroslav@557: * same runtime type is allocated for this purpose. jaroslav@557: * @return an array containing the elements of the list jaroslav@557: * @throws ArrayStoreException if the runtime type of the specified array jaroslav@557: * is not a supertype of the runtime type of every element in jaroslav@557: * this list jaroslav@557: * @throws NullPointerException if the specified array is null jaroslav@557: */ jaroslav@557: @SuppressWarnings("unchecked") jaroslav@557: public T[] toArray(T[] a) { jaroslav@557: if (a.length < size) jaroslav@557: // Make a new array of a's runtime type, but my contents: jaroslav@557: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); jaroslav@557: System.arraycopy(elementData, 0, a, 0, size); jaroslav@557: if (a.length > size) jaroslav@557: a[size] = null; jaroslav@557: return a; jaroslav@557: } jaroslav@557: jaroslav@557: // Positional Access Operations jaroslav@557: jaroslav@557: @SuppressWarnings("unchecked") jaroslav@557: E elementData(int index) { jaroslav@557: return (E) elementData[index]; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns the element at the specified position in this list. jaroslav@557: * jaroslav@557: * @param index index of the element to return jaroslav@557: * @return the element at the specified position in this list jaroslav@557: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@557: */ jaroslav@557: public E get(int index) { jaroslav@557: rangeCheck(index); jaroslav@557: jaroslav@557: return elementData(index); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Replaces the element at the specified position in this list with jaroslav@557: * the specified element. jaroslav@557: * jaroslav@557: * @param index index of the element to replace jaroslav@557: * @param element element to be stored at the specified position jaroslav@557: * @return the element previously at the specified position jaroslav@557: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@557: */ jaroslav@557: public E set(int index, E element) { jaroslav@557: rangeCheck(index); jaroslav@557: jaroslav@557: E oldValue = elementData(index); jaroslav@557: elementData[index] = element; jaroslav@557: return oldValue; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Appends the specified element to the end of this list. jaroslav@557: * jaroslav@557: * @param e element to be appended to this list jaroslav@557: * @return true (as specified by {@link Collection#add}) jaroslav@557: */ jaroslav@557: public boolean add(E e) { jaroslav@557: ensureCapacityInternal(size + 1); // Increments modCount!! jaroslav@557: elementData[size++] = e; jaroslav@557: return true; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Inserts the specified element at the specified position in this jaroslav@557: * list. Shifts the element currently at that position (if any) and jaroslav@557: * any subsequent elements to the right (adds one to their indices). jaroslav@557: * jaroslav@557: * @param index index at which the specified element is to be inserted jaroslav@557: * @param element element to be inserted jaroslav@557: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@557: */ jaroslav@557: public void add(int index, E element) { jaroslav@557: rangeCheckForAdd(index); jaroslav@557: jaroslav@557: ensureCapacityInternal(size + 1); // Increments modCount!! jaroslav@557: System.arraycopy(elementData, index, elementData, index + 1, jaroslav@557: size - index); jaroslav@557: elementData[index] = element; jaroslav@557: size++; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Removes the element at the specified position in this list. jaroslav@557: * Shifts any subsequent elements to the left (subtracts one from their jaroslav@557: * indices). jaroslav@557: * jaroslav@557: * @param index the index of the element to be removed jaroslav@557: * @return the element that was removed from the list jaroslav@557: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@557: */ jaroslav@557: public E remove(int index) { jaroslav@557: rangeCheck(index); jaroslav@557: jaroslav@557: modCount++; jaroslav@557: E oldValue = elementData(index); jaroslav@557: jaroslav@557: int numMoved = size - index - 1; jaroslav@557: if (numMoved > 0) jaroslav@557: System.arraycopy(elementData, index+1, elementData, index, jaroslav@557: numMoved); jaroslav@557: elementData[--size] = null; // Let gc do its work jaroslav@557: jaroslav@557: return oldValue; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Removes the first occurrence of the specified element from this list, jaroslav@557: * if it is present. If the list does not contain the element, it is jaroslav@557: * unchanged. More formally, removes the element with the lowest index jaroslav@557: * i such that jaroslav@557: * (o==null ? get(i)==null : o.equals(get(i))) jaroslav@557: * (if such an element exists). Returns true if this list jaroslav@557: * contained the specified element (or equivalently, if this list jaroslav@557: * changed as a result of the call). jaroslav@557: * jaroslav@557: * @param o element to be removed from this list, if present jaroslav@557: * @return true if this list contained the specified element jaroslav@557: */ jaroslav@557: public boolean remove(Object o) { jaroslav@557: if (o == null) { jaroslav@557: for (int index = 0; index < size; index++) jaroslav@557: if (elementData[index] == null) { jaroslav@557: fastRemove(index); jaroslav@557: return true; jaroslav@557: } jaroslav@557: } else { jaroslav@557: for (int index = 0; index < size; index++) jaroslav@557: if (o.equals(elementData[index])) { jaroslav@557: fastRemove(index); jaroslav@557: return true; jaroslav@557: } jaroslav@557: } jaroslav@557: return false; jaroslav@557: } jaroslav@557: jaroslav@557: /* jaroslav@557: * Private remove method that skips bounds checking and does not jaroslav@557: * return the value removed. jaroslav@557: */ jaroslav@557: private void fastRemove(int index) { jaroslav@557: modCount++; jaroslav@557: int numMoved = size - index - 1; jaroslav@557: if (numMoved > 0) jaroslav@557: System.arraycopy(elementData, index+1, elementData, index, jaroslav@557: numMoved); jaroslav@557: elementData[--size] = null; // Let gc do its work jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Removes all of the elements from this list. The list will jaroslav@557: * be empty after this call returns. jaroslav@557: */ jaroslav@557: public void clear() { jaroslav@557: modCount++; jaroslav@557: jaroslav@557: // Let gc do its work jaroslav@557: for (int i = 0; i < size; i++) jaroslav@557: elementData[i] = null; jaroslav@557: jaroslav@557: size = 0; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Appends all of the elements in the specified collection to the end of jaroslav@557: * this list, in the order that they are returned by the jaroslav@557: * specified collection's Iterator. The behavior of this operation is jaroslav@557: * undefined if the specified collection is modified while the operation jaroslav@557: * is in progress. (This implies that the behavior of this call is jaroslav@557: * undefined if the specified collection is this list, and this jaroslav@557: * list is nonempty.) jaroslav@557: * jaroslav@557: * @param c collection containing elements to be added to this list jaroslav@557: * @return true if this list changed as a result of the call jaroslav@557: * @throws NullPointerException if the specified collection is null jaroslav@557: */ jaroslav@557: public boolean addAll(Collection c) { jaroslav@557: Object[] a = c.toArray(); jaroslav@557: int numNew = a.length; jaroslav@557: ensureCapacityInternal(size + numNew); // Increments modCount jaroslav@557: System.arraycopy(a, 0, elementData, size, numNew); jaroslav@557: size += numNew; jaroslav@557: return numNew != 0; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Inserts all of the elements in the specified collection into this jaroslav@557: * list, starting at the specified position. Shifts the element jaroslav@557: * currently at that position (if any) and any subsequent elements to jaroslav@557: * the right (increases their indices). The new elements will appear jaroslav@557: * in the list in the order that they are returned by the jaroslav@557: * specified collection's iterator. jaroslav@557: * jaroslav@557: * @param index index at which to insert the first element from the jaroslav@557: * specified collection jaroslav@557: * @param c collection containing elements to be added to this list jaroslav@557: * @return true if this list changed as a result of the call jaroslav@557: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@557: * @throws NullPointerException if the specified collection is null jaroslav@557: */ jaroslav@557: public boolean addAll(int index, Collection c) { jaroslav@557: rangeCheckForAdd(index); jaroslav@557: jaroslav@557: Object[] a = c.toArray(); jaroslav@557: int numNew = a.length; jaroslav@557: ensureCapacityInternal(size + numNew); // Increments modCount jaroslav@557: jaroslav@557: int numMoved = size - index; jaroslav@557: if (numMoved > 0) jaroslav@557: System.arraycopy(elementData, index, elementData, index + numNew, jaroslav@557: numMoved); jaroslav@557: jaroslav@557: System.arraycopy(a, 0, elementData, index, numNew); jaroslav@557: size += numNew; jaroslav@557: return numNew != 0; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Removes from this list all of the elements whose index is between jaroslav@557: * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. jaroslav@557: * Shifts any succeeding elements to the left (reduces their index). jaroslav@557: * This call shortens the list by {@code (toIndex - fromIndex)} elements. jaroslav@557: * (If {@code toIndex==fromIndex}, this operation has no effect.) jaroslav@557: * jaroslav@557: * @throws IndexOutOfBoundsException if {@code fromIndex} or jaroslav@557: * {@code toIndex} is out of range jaroslav@557: * ({@code fromIndex < 0 || jaroslav@557: * fromIndex >= size() || jaroslav@557: * toIndex > size() || jaroslav@557: * toIndex < fromIndex}) jaroslav@557: */ jaroslav@557: protected void removeRange(int fromIndex, int toIndex) { jaroslav@557: modCount++; jaroslav@557: int numMoved = size - toIndex; jaroslav@557: System.arraycopy(elementData, toIndex, elementData, fromIndex, jaroslav@557: numMoved); jaroslav@557: jaroslav@557: // Let gc do its work jaroslav@557: int newSize = size - (toIndex-fromIndex); jaroslav@557: while (size != newSize) jaroslav@557: elementData[--size] = null; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Checks if the given index is in range. If not, throws an appropriate jaroslav@557: * runtime exception. This method does *not* check if the index is jaroslav@557: * negative: It is always used immediately prior to an array access, jaroslav@557: * which throws an ArrayIndexOutOfBoundsException if index is negative. jaroslav@557: */ jaroslav@557: private void rangeCheck(int index) { jaroslav@557: if (index >= size) jaroslav@557: throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * A version of rangeCheck used by add and addAll. jaroslav@557: */ jaroslav@557: private void rangeCheckForAdd(int index) { jaroslav@557: if (index > size || index < 0) jaroslav@557: throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Constructs an IndexOutOfBoundsException detail message. jaroslav@557: * Of the many possible refactorings of the error handling code, jaroslav@557: * this "outlining" performs best with both server and client VMs. jaroslav@557: */ jaroslav@557: private String outOfBoundsMsg(int index) { jaroslav@557: return "Index: "+index+", Size: "+size; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Removes from this list all of its elements that are contained in the jaroslav@557: * specified collection. jaroslav@557: * jaroslav@557: * @param c collection containing elements to be removed from this list jaroslav@557: * @return {@code true} if this list changed as a result of the call jaroslav@557: * @throws ClassCastException if the class of an element of this list jaroslav@557: * is incompatible with the specified collection jaroslav@557: * (optional) jaroslav@557: * @throws NullPointerException if this list contains a null element and the jaroslav@557: * specified collection does not permit null elements jaroslav@557: * (optional), jaroslav@557: * or if the specified collection is null jaroslav@557: * @see Collection#contains(Object) jaroslav@557: */ jaroslav@557: public boolean removeAll(Collection c) { jaroslav@557: return batchRemove(c, false); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Retains only the elements in this list that are contained in the jaroslav@557: * specified collection. In other words, removes from this list all jaroslav@557: * of its elements that are not contained in the specified collection. jaroslav@557: * jaroslav@557: * @param c collection containing elements to be retained in this list jaroslav@557: * @return {@code true} if this list changed as a result of the call jaroslav@557: * @throws ClassCastException if the class of an element of this list jaroslav@557: * is incompatible with the specified collection jaroslav@557: * (optional) jaroslav@557: * @throws NullPointerException if this list contains a null element and the jaroslav@557: * specified collection does not permit null elements jaroslav@557: * (optional), jaroslav@557: * or if the specified collection is null jaroslav@557: * @see Collection#contains(Object) jaroslav@557: */ jaroslav@557: public boolean retainAll(Collection c) { jaroslav@557: return batchRemove(c, true); jaroslav@557: } jaroslav@557: jaroslav@557: private boolean batchRemove(Collection c, boolean complement) { jaroslav@557: final Object[] elementData = this.elementData; jaroslav@557: int r = 0, w = 0; jaroslav@557: boolean modified = false; jaroslav@557: try { jaroslav@557: for (; r < size; r++) jaroslav@557: if (c.contains(elementData[r]) == complement) jaroslav@557: elementData[w++] = elementData[r]; jaroslav@557: } finally { jaroslav@557: // Preserve behavioral compatibility with AbstractCollection, jaroslav@557: // even if c.contains() throws. jaroslav@557: if (r != size) { jaroslav@557: System.arraycopy(elementData, r, jaroslav@557: elementData, w, jaroslav@557: size - r); jaroslav@557: w += size - r; jaroslav@557: } jaroslav@557: if (w != size) { jaroslav@557: for (int i = w; i < size; i++) jaroslav@557: elementData[i] = null; jaroslav@557: modCount += size - w; jaroslav@557: size = w; jaroslav@557: modified = true; jaroslav@557: } jaroslav@557: } jaroslav@557: return modified; jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns a list iterator over the elements in this list (in proper jaroslav@557: * sequence), starting at the specified position in the list. jaroslav@557: * The specified index indicates the first element that would be jaroslav@557: * returned by an initial call to {@link ListIterator#next next}. jaroslav@557: * An initial call to {@link ListIterator#previous previous} would jaroslav@557: * return the element with the specified index minus one. jaroslav@557: * jaroslav@557: *

The returned list iterator is fail-fast. jaroslav@557: * jaroslav@557: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@557: */ jaroslav@557: public ListIterator listIterator(int index) { jaroslav@557: if (index < 0 || index > size) jaroslav@557: throw new IndexOutOfBoundsException("Index: "+index); jaroslav@557: return new ListItr(index); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns a list iterator over the elements in this list (in proper jaroslav@557: * sequence). jaroslav@557: * jaroslav@557: *

The returned list iterator is fail-fast. jaroslav@557: * jaroslav@557: * @see #listIterator(int) jaroslav@557: */ jaroslav@557: public ListIterator listIterator() { jaroslav@557: return new ListItr(0); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns an iterator over the elements in this list in proper sequence. jaroslav@557: * jaroslav@557: *

The returned iterator is fail-fast. jaroslav@557: * jaroslav@557: * @return an iterator over the elements in this list in proper sequence jaroslav@557: */ jaroslav@557: public Iterator iterator() { jaroslav@557: return new Itr(); jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * An optimized version of AbstractList.Itr jaroslav@557: */ jaroslav@557: private class Itr implements Iterator { jaroslav@557: int cursor; // index of next element to return jaroslav@557: int lastRet = -1; // index of last element returned; -1 if no such jaroslav@557: int expectedModCount = modCount; jaroslav@557: jaroslav@557: public boolean hasNext() { jaroslav@557: return cursor != size; jaroslav@557: } jaroslav@557: jaroslav@557: @SuppressWarnings("unchecked") jaroslav@557: public E next() { jaroslav@557: checkForComodification(); jaroslav@557: int i = cursor; jaroslav@557: if (i >= size) jaroslav@557: throw new NoSuchElementException(); jaroslav@557: Object[] elementData = ArrayList.this.elementData; jaroslav@557: if (i >= elementData.length) jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: cursor = i + 1; jaroslav@557: return (E) elementData[lastRet = i]; jaroslav@557: } jaroslav@557: jaroslav@557: public void remove() { jaroslav@557: if (lastRet < 0) jaroslav@557: throw new IllegalStateException(); jaroslav@557: checkForComodification(); jaroslav@557: jaroslav@557: try { jaroslav@557: ArrayList.this.remove(lastRet); jaroslav@557: cursor = lastRet; jaroslav@557: lastRet = -1; jaroslav@557: expectedModCount = modCount; jaroslav@557: } catch (IndexOutOfBoundsException ex) { jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: final void checkForComodification() { jaroslav@557: if (modCount != expectedModCount) jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * An optimized version of AbstractList.ListItr jaroslav@557: */ jaroslav@557: private class ListItr extends Itr implements ListIterator { jaroslav@557: ListItr(int index) { jaroslav@557: super(); jaroslav@557: cursor = index; jaroslav@557: } jaroslav@557: jaroslav@557: public boolean hasPrevious() { jaroslav@557: return cursor != 0; jaroslav@557: } jaroslav@557: jaroslav@557: public int nextIndex() { jaroslav@557: return cursor; jaroslav@557: } jaroslav@557: jaroslav@557: public int previousIndex() { jaroslav@557: return cursor - 1; jaroslav@557: } jaroslav@557: jaroslav@557: @SuppressWarnings("unchecked") jaroslav@557: public E previous() { jaroslav@557: checkForComodification(); jaroslav@557: int i = cursor - 1; jaroslav@557: if (i < 0) jaroslav@557: throw new NoSuchElementException(); jaroslav@557: Object[] elementData = ArrayList.this.elementData; jaroslav@557: if (i >= elementData.length) jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: cursor = i; jaroslav@557: return (E) elementData[lastRet = i]; jaroslav@557: } jaroslav@557: jaroslav@557: public void set(E e) { jaroslav@557: if (lastRet < 0) jaroslav@557: throw new IllegalStateException(); jaroslav@557: checkForComodification(); jaroslav@557: jaroslav@557: try { jaroslav@557: ArrayList.this.set(lastRet, e); jaroslav@557: } catch (IndexOutOfBoundsException ex) { jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: public void add(E e) { jaroslav@557: checkForComodification(); jaroslav@557: jaroslav@557: try { jaroslav@557: int i = cursor; jaroslav@557: ArrayList.this.add(i, e); jaroslav@557: cursor = i + 1; jaroslav@557: lastRet = -1; jaroslav@557: expectedModCount = modCount; jaroslav@557: } catch (IndexOutOfBoundsException ex) { jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: /** jaroslav@557: * Returns a view of the portion of this list between the specified jaroslav@557: * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If jaroslav@557: * {@code fromIndex} and {@code toIndex} are equal, the returned list is jaroslav@557: * empty.) The returned list is backed by this list, so non-structural jaroslav@557: * changes in the returned list are reflected in this list, and vice-versa. jaroslav@557: * The returned list supports all of the optional list operations. jaroslav@557: * jaroslav@557: *

This method eliminates the need for explicit range operations (of jaroslav@557: * the sort that commonly exist for arrays). Any operation that expects jaroslav@557: * a list can be used as a range operation by passing a subList view jaroslav@557: * instead of a whole list. For example, the following idiom jaroslav@557: * removes a range of elements from a list: jaroslav@557: *

jaroslav@557:      *      list.subList(from, to).clear();
jaroslav@557:      * 
jaroslav@557: * Similar idioms may be constructed for {@link #indexOf(Object)} and jaroslav@557: * {@link #lastIndexOf(Object)}, and all of the algorithms in the jaroslav@557: * {@link Collections} class can be applied to a subList. jaroslav@557: * jaroslav@557: *

The semantics of the list returned by this method become undefined if jaroslav@557: * the backing list (i.e., this list) is structurally modified in jaroslav@557: * any way other than via the returned list. (Structural modifications are jaroslav@557: * those that change the size of this list, or otherwise perturb it in such jaroslav@557: * a fashion that iterations in progress may yield incorrect results.) jaroslav@557: * jaroslav@557: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@557: * @throws IllegalArgumentException {@inheritDoc} jaroslav@557: */ jaroslav@557: public List subList(int fromIndex, int toIndex) { jaroslav@557: subListRangeCheck(fromIndex, toIndex, size); jaroslav@557: return new SubList(this, 0, fromIndex, toIndex); jaroslav@557: } jaroslav@557: jaroslav@557: static void subListRangeCheck(int fromIndex, int toIndex, int size) { jaroslav@557: if (fromIndex < 0) jaroslav@557: throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); jaroslav@557: if (toIndex > size) jaroslav@557: throw new IndexOutOfBoundsException("toIndex = " + toIndex); jaroslav@557: if (fromIndex > toIndex) jaroslav@557: throw new IllegalArgumentException("fromIndex(" + fromIndex + jaroslav@557: ") > toIndex(" + toIndex + ")"); jaroslav@557: } jaroslav@557: jaroslav@557: private class SubList extends AbstractList implements RandomAccess { jaroslav@557: private final AbstractList parent; jaroslav@557: private final int parentOffset; jaroslav@557: private final int offset; jaroslav@557: int size; jaroslav@557: jaroslav@557: SubList(AbstractList parent, jaroslav@557: int offset, int fromIndex, int toIndex) { jaroslav@557: this.parent = parent; jaroslav@557: this.parentOffset = fromIndex; jaroslav@557: this.offset = offset + fromIndex; jaroslav@557: this.size = toIndex - fromIndex; jaroslav@557: this.modCount = ArrayList.this.modCount; jaroslav@557: } jaroslav@557: jaroslav@557: public E set(int index, E e) { jaroslav@557: rangeCheck(index); jaroslav@557: checkForComodification(); jaroslav@557: E oldValue = ArrayList.this.elementData(offset + index); jaroslav@557: ArrayList.this.elementData[offset + index] = e; jaroslav@557: return oldValue; jaroslav@557: } jaroslav@557: jaroslav@557: public E get(int index) { jaroslav@557: rangeCheck(index); jaroslav@557: checkForComodification(); jaroslav@557: return ArrayList.this.elementData(offset + index); jaroslav@557: } jaroslav@557: jaroslav@557: public int size() { jaroslav@557: checkForComodification(); jaroslav@557: return this.size; jaroslav@557: } jaroslav@557: jaroslav@557: public void add(int index, E e) { jaroslav@557: rangeCheckForAdd(index); jaroslav@557: checkForComodification(); jaroslav@557: parent.add(parentOffset + index, e); jaroslav@557: this.modCount = parent.modCount; jaroslav@557: this.size++; jaroslav@557: } jaroslav@557: jaroslav@557: public E remove(int index) { jaroslav@557: rangeCheck(index); jaroslav@557: checkForComodification(); jaroslav@557: E result = parent.remove(parentOffset + index); jaroslav@557: this.modCount = parent.modCount; jaroslav@557: this.size--; jaroslav@557: return result; jaroslav@557: } jaroslav@557: jaroslav@557: protected void removeRange(int fromIndex, int toIndex) { jaroslav@557: checkForComodification(); jaroslav@557: parent.removeRange(parentOffset + fromIndex, jaroslav@557: parentOffset + toIndex); jaroslav@557: this.modCount = parent.modCount; jaroslav@557: this.size -= toIndex - fromIndex; jaroslav@557: } jaroslav@557: jaroslav@557: public boolean addAll(Collection c) { jaroslav@557: return addAll(this.size, c); jaroslav@557: } jaroslav@557: jaroslav@557: public boolean addAll(int index, Collection c) { jaroslav@557: rangeCheckForAdd(index); jaroslav@557: int cSize = c.size(); jaroslav@557: if (cSize==0) jaroslav@557: return false; jaroslav@557: jaroslav@557: checkForComodification(); jaroslav@557: parent.addAll(parentOffset + index, c); jaroslav@557: this.modCount = parent.modCount; jaroslav@557: this.size += cSize; jaroslav@557: return true; jaroslav@557: } jaroslav@557: jaroslav@557: public Iterator iterator() { jaroslav@557: return listIterator(); jaroslav@557: } jaroslav@557: jaroslav@557: public ListIterator listIterator(final int index) { jaroslav@557: checkForComodification(); jaroslav@557: rangeCheckForAdd(index); jaroslav@557: final int offset = this.offset; jaroslav@557: jaroslav@557: return new ListIterator() { jaroslav@557: int cursor = index; jaroslav@557: int lastRet = -1; jaroslav@557: int expectedModCount = ArrayList.this.modCount; jaroslav@557: jaroslav@557: public boolean hasNext() { jaroslav@557: return cursor != SubList.this.size; jaroslav@557: } jaroslav@557: jaroslav@557: @SuppressWarnings("unchecked") jaroslav@557: public E next() { jaroslav@557: checkForComodification(); jaroslav@557: int i = cursor; jaroslav@557: if (i >= SubList.this.size) jaroslav@557: throw new NoSuchElementException(); jaroslav@557: Object[] elementData = ArrayList.this.elementData; jaroslav@557: if (offset + i >= elementData.length) jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: cursor = i + 1; jaroslav@557: return (E) elementData[offset + (lastRet = i)]; jaroslav@557: } jaroslav@557: jaroslav@557: public boolean hasPrevious() { jaroslav@557: return cursor != 0; jaroslav@557: } jaroslav@557: jaroslav@557: @SuppressWarnings("unchecked") jaroslav@557: public E previous() { jaroslav@557: checkForComodification(); jaroslav@557: int i = cursor - 1; jaroslav@557: if (i < 0) jaroslav@557: throw new NoSuchElementException(); jaroslav@557: Object[] elementData = ArrayList.this.elementData; jaroslav@557: if (offset + i >= elementData.length) jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: cursor = i; jaroslav@557: return (E) elementData[offset + (lastRet = i)]; jaroslav@557: } jaroslav@557: jaroslav@557: public int nextIndex() { jaroslav@557: return cursor; jaroslav@557: } jaroslav@557: jaroslav@557: public int previousIndex() { jaroslav@557: return cursor - 1; jaroslav@557: } jaroslav@557: jaroslav@557: public void remove() { jaroslav@557: if (lastRet < 0) jaroslav@557: throw new IllegalStateException(); jaroslav@557: checkForComodification(); jaroslav@557: jaroslav@557: try { jaroslav@557: SubList.this.remove(lastRet); jaroslav@557: cursor = lastRet; jaroslav@557: lastRet = -1; jaroslav@557: expectedModCount = ArrayList.this.modCount; jaroslav@557: } catch (IndexOutOfBoundsException ex) { jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: public void set(E e) { jaroslav@557: if (lastRet < 0) jaroslav@557: throw new IllegalStateException(); jaroslav@557: checkForComodification(); jaroslav@557: jaroslav@557: try { jaroslav@557: ArrayList.this.set(offset + lastRet, e); jaroslav@557: } catch (IndexOutOfBoundsException ex) { jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: public void add(E e) { jaroslav@557: checkForComodification(); jaroslav@557: jaroslav@557: try { jaroslav@557: int i = cursor; jaroslav@557: SubList.this.add(i, e); jaroslav@557: cursor = i + 1; jaroslav@557: lastRet = -1; jaroslav@557: expectedModCount = ArrayList.this.modCount; jaroslav@557: } catch (IndexOutOfBoundsException ex) { jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: } jaroslav@557: jaroslav@557: final void checkForComodification() { jaroslav@557: if (expectedModCount != ArrayList.this.modCount) jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: }; jaroslav@557: } jaroslav@557: jaroslav@557: public List subList(int fromIndex, int toIndex) { jaroslav@557: subListRangeCheck(fromIndex, toIndex, size); jaroslav@557: return new SubList(this, offset, fromIndex, toIndex); jaroslav@557: } jaroslav@557: jaroslav@557: private void rangeCheck(int index) { jaroslav@557: if (index < 0 || index >= this.size) jaroslav@557: throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); jaroslav@557: } jaroslav@557: jaroslav@557: private void rangeCheckForAdd(int index) { jaroslav@557: if (index < 0 || index > this.size) jaroslav@557: throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); jaroslav@557: } jaroslav@557: jaroslav@557: private String outOfBoundsMsg(int index) { jaroslav@557: return "Index: "+index+", Size: "+this.size; jaroslav@557: } jaroslav@557: jaroslav@557: private void checkForComodification() { jaroslav@557: if (ArrayList.this.modCount != this.modCount) jaroslav@557: throw new ConcurrentModificationException(); jaroslav@557: } jaroslav@557: } jaroslav@557: }