- java.lang.Object
-
- java.util.AbstractCollection<E>
-
- java.util.AbstractList<E>
-
- java.util.ArrayList<E>
-
- Parameter Type
-
E- The element type in this list
- All Implemented Interfaces
-
Serializable,Cloneable,Iterable<E>,Collection<E>,List<E>,RandomAccess
- Known Direct Subclasses:
-
AttributeList,RoleList,RoleUnresolvedList
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
ListResizable array implementation of the interface. Implements all optional list operations and permits all elements, includingnull。 except implementationListIn addition to the interface, this class also provides some methods to manipulate the size of the array used internally to store the list. (This class is roughly equivalent toVector, except that it is not synchronized.)that
size,isEmpty,get,set,iteratorandlistIteratorThe operation runs in constant time.addoperates inamortized constant timeruns, that is, adding n elements requires O(n) time. All other operations run in linear time (roughly speaking). andLinkedListCompared with the implementation, the constant factor is lower.each
ArrayListeach instance has aCapacity 。 The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity automatically increases. Other than the fact that adding elements has constant amortized time cost, the details of the growth strategy are not specified.When using
ensureCapacityBefore an operation adds a large number of elements, the application can increaseArrayListthe capacity of the instance. This may reduce the number of incremental reallocations.Note that this implementation is not synchronized. If multiple threads access simultaneously
ArrayListinstance, and at least one thread has structurally modified the list, thenRequiredSynchronize externally. (StructuremodifyYesaddorDeleteaor multipleelement'sanyOperation, or显formula调整BackuparrayofSize;onlySettingselement'sThe value is notStructuremodify。)这通常Throughsame步one些自butEncapsulationobject ofto implement.name单。 If such an object does not exist, you should useCollections.synchronizedListThe method “wraps” the list. This is best done at creation time, to prevent accidental unsynchronized access to the list:List list = Collections.synchronizedList(new ArrayList(...));This type of
iteratorandlistIteratorThe iterator returned by the method isfail-fast: if the list is structurally modified at any time after the iterator is created, except through the iterator's ownremoveoraddExcept through the method, the iterator will throwConcurrentModificationException。 Therefore, in the case of concurrent modification, the iterator fails fast and cleanly, rather than risking arbitrary, non-deterministic behavior at an unspecified time in the future.Please note that the fail-fast behavior of iterators cannot be guaranteed, because in general, it is impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw on a best-effort basis
ConcurrentModificationException。 Therefore, it is incorrect to write programs that depend on this exception to ensure their correctness:The fail-fast behavior of an iterator should be used only to detect bugs.this course isJava Collections Frameworkthe member.
- Starting from the following version:
- 1.2
- See also:
-
Collection,List,LinkedList,Vector, Serialized Form
-
-
field summary
-
Declared fields in class java.util.AbstractList
modCount
-
-
Constructor Summary
Constructor Constructor Description ArrayList()Constructs an empty list with an initial capacity of ten.ArrayList(int initialCapacity)Constructs an empty list with the specified initial capacity.ArrayList(Collection<? extends E> c)Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
-
method summary
All methods Instance Methods Specific Methods Variables and types Methods Description voidadd(int index, E element)Inserts the specified element at the specified position in this list.booleanadd(E e)Appends the specified element to the end of this list.booleanaddAll(int index, Collection<? extends E> c)Inserts all elements from the specified collection into this list, starting at the specified position.booleanaddAll(Collection<? extends E> c)Appends all elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.voidclear()Remove all elements from this list.Objectclone()Return thisArrayListA shallow copy of the instance.booleancontains(Object o)If this list contains the specified element, then returns.true。voidensureCapacity(int minCapacity)If necessary, increase thisArrayListthe capacity of the instance, to ensure that it can hold at least the number of elements specified by the minimum capacity parameter.voidforEach(Consumer<? super E> action)PairIterablePerforms the given operation on each element until processed.IterableAll elements or operations throw an exception.Eget(int index)Returns the element at the specified position in this list.intindexOf(Object o)Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.booleanisEmpty()If this list contains no elements, returnstrue。Iterator<E>iterator()Returns an iterator over the elements in this list in proper sequence.intlastIndexOf(Object o)Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.ListIterator<E>listIterator()Returns a list iterator over the elements in this list (in proper sequence).ListIterator<E>listIterator(int index)Returns a list iterator over the elements in this list, starting at the specified position in the list (in the correct order).Eremove(int index)Removes the element at the specified position in this list.booleanremove(Object o)Removes the first occurrence of the specified element from this list, if it is present.booleanremoveAll(Collection<?> c)Removes from this list all elements contained in the specified collection.booleanremoveIf(Predicate<? super E> filter)Removes all elements in this collection that satisfy the given predicate.protected voidremoveRange(int fromIndex, int toIndex)Removes from this list all elements whose index is betweenfromIndex(inclusive) andtoIndexAll elements between (exclusive).booleanretainAll(Collection<?> c)Retains only the elements in this list that are contained in the specified collection.Eset(int index, E element)Replaces the element at the specified position in this list with the specified element.intsize()Returns the number of elements in this list.Spliterator<E>spliterator()Created over the elements in this listlate-bindingandFail-fastSpliterator。List<E>subList(int fromIndex, int toIndex)Returns the specifiedfromIndex(inclusive) andtoIndexView of this portion of the list between (exclusive).Object[]toArray()Returns an array containing all elements in this list in proper order (from the first element to the last element).<T> T[]toArray(T[] a)Returns an array containing all elements in this list in proper order (from the first element to the last element); The runtime type of the returned array is the runtime type of the specified array.voidtrimToSize()Put thisArrayListThe capacity of the instance is adjusted to the current size of the list.-
Class declaring the method: java.util.AbstractList
equals, hashCode
-
Class declaring the method: java.util.AbstractCollection
containsAll, toString
-
Class declaring the method: java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
-
Interface declaring the method: java.util.Collection
parallelStream, stream, toArray
-
Interface declaring the method: java.util.List
containsAll, equals, hashCode, replaceAll, sort
-
-
-
-
Constructor Details
-
ArrayList
public ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.- Parameter
-
initialCapacity- The initial capacity of the list - Exception
-
IllegalArgumentException- If the specified initial capacity is negative
-
ArrayList
public ArrayList()
Constructs an empty list with an initial capacity of ten.
-
ArrayList
public ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.- Parameter
-
c-cThe collection whose elements are to be placed into this list - Exception
-
NullPointerException- If the specified collection is null
-
-
Method Details
-
trimToSize
public void trimToSize()
Put thisArrayListThe capacity of the instance is adjusted to the current size of the list. An application can use this operation to minimizeArrayListthe storage of the instance.
-
ensureCapacity
public void ensureCapacity(int minCapacity)
If necessary, increase thisArrayListthe capacity of the instance, to ensure that it can hold at least the number of elements specified by the minimum capacity parameter.- Parameter
-
minCapacity- The minimum required capacity
-
size
public int size()
Returns the number of elements in this list.
-
isEmpty
public boolean isEmpty()
If this list contains no elements, returnstrue。- Specified by:
-
isEmptyIn the interfaceCollection<E> - Specified by:
-
isEmpty, interfaceList<E> - Override:
-
isEmptyin the courseAbstractCollection<E> - Result
-
trueIf this list contains no elements
-
contains
public boolean contains(Object o)
If this list contains the specified element, then returns.true。 More formally, returnstrueIf and only if this list contains at least one elementeObjects.equals(o, e)。- Specified by:
-
containsIn the interfaceCollection<E> - Specified by:
-
containsIn the interfaceList<E> - Override:
-
containsin the courseAbstractCollection<E> - Parameter
-
o- the element whose presence in this list is to be tested - Result
-
trueIf this list contains the specified element
-
indexOf
public int indexOf(Object o)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest indexiFor exampleObjects.equals(o, get(i)), or -1 if there is no such index.
-
lastIndexOf
public int lastIndexOf(Object o)
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the highest index.iFor exampleObjects.equals(o, get(i)), or -1 if there is no such index.- Specified by:
-
lastIndexOfIn the interfaceList<E> - Override:
-
lastIndexOfin class.AbstractList<E> - Parameter
-
o- the element to search for - Result
- the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element
-
clone
public Object clone()
Return thisArrayListA shallow copy of the instance. (The elements themselves are not copied.)
-
toArray
public Object[] toArray()
Returns an array containing all elements in this list in proper order (from the first element to the last element).The returned array will be "safe" because this list does not retain references to it. (In other words, this method must allocate a new array). Thus the caller is free to modify the returned array.
This method acts as a bridge between array-based and collection-based APIs.
- Specified by:
-
toArray, interfaceCollection<E> - Specified by:
-
toArrayIn the interfaceList<E> - Override:
-
toArrayin the courseAbstractCollection<E> - Result
- an array containing all of the elements in this list in proper order
- See also:
-
Arrays.asList(Object[])
-
toArray
public <T> T[] toArray(T[] a)
Returns an array containing all elements in this list in proper order (from the first element to the last element); The runtime type of the returned array is the runtime type of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to
null。 ( onlyWhen the caller knows that the list does not contain any null elements, this is useful in determining the length of the list.)- Specified by:
-
toArray, interfaceCollection<E> - Specified by:
-
toArray, interfaceList<E> - Override:
-
toArrayin the courseAbstractCollection<E> - Parameter Type
-
T- the component type of the array to contain the collection - Parameter
-
a- the array to store the list elements, if it is large enough; Otherwise, a new array of the same runtime type is allocated for this purpose. - Result
- An array containing the elements of the list
- Exception
-
ArrayStoreException- If the runtime type of the specified array is not a supertype of the runtime type of every element in this list -
NullPointerException- If the specified array is null
-
get
public E get(int index)
Returns the element at the specified position in this list.- Specified by:
-
get, interfaceList<E> - Specified by:
-
getin the courseAbstractList<E> - Parameter
-
index- The index of the element to return - Result
- The element at the specified position in this list
- Exception
-
IndexOutOfBoundsException- If the index is out of range (index < 0 || index >= size())
-
set
public E set(int index, E element)
Replaces the element at the specified position in this list with the specified element.- Specified by:
-
set, interfaceList<E> - Override:
-
setin the courseAbstractList<E> - Parameter
-
index- The index of the element to replace -
element- The element to be stored at the specified position - Result
- The element previously at the specified position
- Exception
-
IndexOutOfBoundsException- If the index is out of range (index < 0 || index >= size())
-
add
public boolean add(E e)
Appends the specified element to the end of this list.- Specified by:
-
add, interfaceCollection<E> - Specified by:
-
addIn the interfaceList<E> - Override:
-
addin the courseAbstractList<E> - Parameter
-
e- The element to be appended to this list - Result
-
true(byCollection.add(E)specified)
-
add
public void add(int index, E element)Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).- Specified by:
-
addin interfaceList<E> - Override:
-
addin the courseAbstractList<E> - Parameter
-
index- The index at which the specified element is to be inserted -
element- The element to be inserted - Exception
-
IndexOutOfBoundsException- If the index is out of range (index < 0 || index > size())
-
remove
public E remove(int index)
Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).- Specified by:
-
removeIn the interfaceList<E> - Override:
-
removein the courseAbstractList<E> - Parameter
-
index- The index of the element to be removed - Result
- The element that was removed from the list
- Exception
-
IndexOutOfBoundsException- If the index is out of range (index < 0 || index >= size())
-
remove
public boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest indexithe elements of, such thatObjects.equals(o, get(i))(if such elements exist). If this list contains the specified element, then returns.true(or equivalently, if this list is changed by the call).- Specified by:
-
removeIn the interfaceCollection<E> - Specified by:
-
removeIn the interfaceList<E> - Override:
-
removein the courseAbstractCollection<E> - Parameter
-
o- the element to be removed from this list, if present - Result
-
trueIf this list contains the specified element
-
clear
public void clear()
Remove all elements from this list. After this call returns, the list will be empty.- Specified by:
-
clearIn the interfaceCollection<E> - Specified by:
-
clearIn the interfaceList<E> - Override:
-
clearin the courseAbstractList<E>
-
addAll
public boolean addAll(Collection<? extends E> c)
Appends all elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. If the specified collection is modified while the operation is in progress, the behavior of this operation is undefined. (This means that if the specified collection is this list, the behavior of this call is undefined, and this list is non-empty.)- Specified by:
-
addAll, interfaceCollection<E> - Specified by:
-
addAllIn the interfaceList<E> - Override:
-
addAllin the courseAbstractCollection<E> - Parameter
-
c- the collection containing elements to be added to this list - Result
-
trueIf this list changed as a result of the call - Exception
-
NullPointerException- If the specified collection is null - See also:
-
AbstractCollection.add(Object)
-
addAll
public boolean addAll(int index, Collection<? extends E> c)Inserts all elements from the specified collection into this list, starting at the specified position. Shifts the element at the current position (if any) and any subsequent elements to the right (increasing their indices). The new elements will appear in the list in the order returned by the specified collection's iterator.- Specified by:
-
addAllIn the interfaceList<E> - Override:
-
addAllin the courseAbstractList<E> - Parameter
-
index- the index at which to insert the first element from the specified collection -
c- the collection containing elements to be added to this list - Result
-
trueIf this list changed as a result of the call - Exception
-
IndexOutOfBoundsException- If the index is out of range (index < 0 || index > size()) -
NullPointerException- If the specified collection is null
-
removeRange
protected void removeRange(int fromIndex, int toIndex)Removes from this list all elements whose index is betweenfromIndex(inclusive) andtoIndexAll elements between (exclusive). Shifts any subsequent elements to the left (decreases their index). this call is made through(toIndex - fromIndex)a list of shortened elements. (iftoIndex==fromIndex, this operation is invalid.)- Override:
-
removeRangein the courseAbstractList<E> - Parameter
-
fromIndex- The index of the first element to be removed -
toIndex- the index after the last element to be removed - Exception
-
IndexOutOfBoundsException- iffromIndexortoIndexout of range (fromIndex < 0 || toIndex > size() || toIndex < fromIndex)
-
removeAll
public boolean removeAll(Collection<?> c)
Removes from this list all elements contained in the specified collection.- Specified by:
-
removeAllIn the interfaceCollection<E> - Specified by:
-
removeAllIn the interfaceList<E> - Override:
-
removeAllin the courseAbstractCollection<E> - Parameter
-
c- the collection containing elements to be removed from this list - Result
-
trueIf this list changed as a result of the call - Exception
-
ClassCastException- if the class of an element of this list is incompatible with the specified collection (optional ) -
NullPointerException- if this list contains a null element and the specified collection does not permit null elements (optional), or the specified collection is null - See also:
-
Collection.contains(Object)
-
retainAll
public boolean retainAll(Collection<?> c)
Retains only the elements in this list that are contained in the specified collection. In other words, remove all elements from this list that are not contained in the specified collection.- Specified by:
-
retainAllIn the interfaceCollection<E> - Specified by:
-
retainAllIn the interfaceList<E> - Override:
-
retainAllin the courseAbstractCollection<E> - Parameter
-
c- the collection containing elements to be retained in this list - Result
-
trueIf this list changed as a result of the call - Exception
-
ClassCastException- if the class of an element of this list is incompatible with the specified collection (optional ) -
NullPointerException- if this list contains a null element and the specified collection does not permit null elements (optional), or the specified collection is null - See also:
-
Collection.contains(Object)
-
listIterator
public ListIterator<E> listIterator(int index)
Returns a list iterator over the elements in this list, starting at the specified position in the list (in the correct order). The specified index indicates the initial callnextThe first element will be returned. PairpreviousThe initial call will return the element at the specified index minus 1.The returned list iterator isfail-fast 。
- Specified by:
-
listIteratorIn the interfaceList<E> - Override:
-
listIteratorin the courseAbstractList<E> - Parameter
-
index- the index of the first element to be returned from the list iterator (by callingnext) - Result
- a list iterator over the elements in this list (in proper order), starting at the specified position in the list
- Exception
-
IndexOutOfBoundsException- If the index is out of range (index < 0 || index > size())
-
listIterator
public ListIterator<E> listIterator()
Returns a list iterator over the elements in this list (in proper sequence).The returned list iterator isfail-fast 。
- Specified by:
-
listIterator, interfaceList<E> - Override:
-
listIteratorin the courseAbstractList<E> - Result
- a list iterator over the elements in this list (in proper order)
- See also:
-
listIterator(int)
-
iterator
public Iterator<E> iterator()
Returns an iterator over the elements in this list in proper sequence.The returned iterator isfail-fast 。
-
subList
public List<E> subList(int fromIndex, int toIndex)
Returns the specifiedfromIndex(inclusive) andtoIndexA view of the portion of this list between (exclusive). (iffromIndexandtoIndexIf 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 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();can beindexOf(Object)andlastIndexOf(Object)Constructs a similar idiom, and canCollectionsAll algorithms in the class apply to sublists.If the backing list (i.e., this list) is instructurallyin any way other than through the returned listVariablethen the semantics of the list returned by this method become undefined. (Structural modifications are those that change the size of this list, or otherwise disturb it in ways that an ongoing iteration may produce incorrect results.)
- Specified by:
-
subList, interfaceList<E> - Override:
-
subListin the courseAbstractList<E> - Parameter
-
fromIndex-fromIndexLow endpoint (inclusive) -
toIndex-toIndexThe high endpoint (exclusive) - Result
- A view of the specified range within this list
- Exception
-
IndexOutOfBoundsException- If the endpoint index values are out of range(fromIndex < 0 || toIndex > size) -
IllegalArgumentException- If the endpoint indices are out of order(fromIndex > toIndex)
-
forEach
public void forEach(Consumer<? super E> action)
Instructions copied from the interface:IterablePairIterablePerforms the given operation on each element until processed.IterableAll elements or operations throw an exception. If the order is specified, the operations are performed in iteration order. Exceptions thrown by the operation are forwarded to the caller.The behavior of this method is unspecified if the operation performs side effects that modify the underlying source of elements, unless the overriding class has specified a concurrent modification policy.
- Specified by:
-
forEachIn the interfaceIterable<E> - Parameter
-
action- The operation to be performed for each element - Exception
-
NullPointerException- If the specified operation is null
-
spliterator
public Spliterator<E> spliterator()
Created over the elements in this listlate-bindingandFail-fastSpliterator。that
SpliteratorReportSpliterator.SIZED,Spliterator.SUBSIZEDandSpliterator.ORDERED。 Overriding implementations should record reports of other characteristic values.- Specified by:
-
spliteratorIn the interfaceCollection<E> - Specified by:
-
spliteratorIn the interfaceIterable<E> - Specified by:
-
spliteratorIn the interfaceList<E> - Result
- Performed on the elements in this list
Spliterator - Starting from the following version:
- 1.8
-
removeIf
public boolean removeIf(Predicate<? super E> filter)
Instructions copied from the interface:CollectionRemoves all elements in this collection that satisfy the given predicate. Errors or runtime exceptions thrown during iteration or by a predicate are relayed to the caller.- Specified by:
-
removeIf, interfaceCollection<E> - Parameter
-
filter- Returns true for elements to be removedtruepredicate of - Result
-
trueWhether any elements were removed - Exception
-
NullPointerException- if the specified filter is null
-
-