public class CopyOnWriteArrayList<E> extends Object implements List<E>, RandomAccess, Cloneable, Serializable
Read operations (including get(int)
) do not block and may overlap with
update operations. Reads reflect the results of the most recently completed
operations. Aggregate operations like addAll(java.util.Collection<? extends E>)
and clear()
are
atomic; they never expose an intermediate state.
Iterators of this list never throw ConcurrentModificationException
. When an iterator is created, it keeps a
copy of the list's contents. It is always safe to iterate this list, but
iterations may not reflect the latest state of the list.
Iterators returned by this list and its sub lists cannot modify the
underlying list. In particular, Iterator.remove()
, ListIterator.add(E)
and ListIterator.set(E)
all throw UnsupportedOperationException
.
This class offers extended API beyond the List
interface. It
includes additional overloads for indexed search (indexOf(E, int)
and lastIndexOf(E, int)
) and methods for conditional adds (addIfAbsent(E)
and
addAllAbsent(java.util.Collection<? extends E>)
).
Constructor and Description |
---|
CopyOnWriteArrayList()
Creates a new empty instance.
|
CopyOnWriteArrayList(Collection<? extends E> collection)
Creates a new instance containing the elements of
collection . |
CopyOnWriteArrayList(E[] array)
Creates a new instance containing the elements of
array . |
Modifier and Type | Method and Description |
---|---|
boolean |
add(E e)
Appends the specified element to the end of this list (optional
operation).
|
void |
add(int index,
E e)
Inserts the specified element at the specified position in this list
(optional operation).
|
boolean |
addAll(Collection<? extends E> collection)
Appends all of the elements in the specified collection to the end of
this list, in the order that they are returned by the specified
collection's iterator (optional operation).
|
boolean |
addAll(int index,
Collection<? extends E> collection)
Inserts all of the elements in the specified collection into this
list at the specified position (optional operation).
|
int |
addAllAbsent(Collection<? extends E> collection)
Adds the elements of
collection that are not already present in
this list. |
boolean |
addIfAbsent(E object)
Adds
object to the end of this list if it is not already present. |
void |
clear()
Removes all of the elements from this list (optional operation).
|
Object |
clone()
Creates and returns a copy of this object.
|
boolean |
contains(Object o)
Returns true if this list contains the specified element.
|
boolean |
containsAll(Collection<?> collection)
Returns true if this list contains all of the elements of the
specified collection.
|
boolean |
equals(Object other)
Indicates whether some other object is "equal to" this one.
|
void |
forEach(Consumer<? super E> action)
Performs the given action for each element of the
Iterable
until all elements have been processed or the action throws an
exception. |
E |
get(int index)
Returns the element at the specified position in this list.
|
int |
hashCode()
Returns a hash code value for the object.
|
int |
indexOf(E object,
int from)
Searches this list for
object and returns the index of the first
occurrence that is at or after from . |
int |
indexOf(Object object)
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
|
boolean |
isEmpty()
Returns true if this list contains no elements.
|
Iterator<E> |
iterator()
Returns an
Iterator that iterates over the elements of this list
as they were at the time of this method call. |
int |
lastIndexOf(E object,
int to)
Searches this list for
object and returns the index of the last
occurrence that is before to . |
int |
lastIndexOf(Object object)
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()
Equivalent to
listIterator(0) . |
ListIterator<E> |
listIterator(int index)
Returns a
ListIterator that iterates over the elements of this
list as they were at the time of this method call. |
E |
remove(int index)
Removes the element at the specified position in this list (optional
operation).
|
boolean |
remove(Object o)
Removes the first occurrence of the specified element from this list,
if it is present (optional operation).
|
boolean |
removeAll(Collection<?> collection)
Removes from this list all of its elements that are contained in the
specified collection (optional operation).
|
void |
replaceAll(UnaryOperator<E> operator)
Replaces each element of this list with the result of applying the
operator to that element.
|
boolean |
retainAll(Collection<?> collection)
Retains only the elements in this list that are contained in the
specified collection (optional operation).
|
E |
set(int index,
E e)
Replaces the element at the specified position in this list with the
specified element (optional operation).
|
int |
size()
Returns the number of elements in this list.
|
void |
sort(Comparator<? super E> c)
Sorts this list using the supplied
Comparator to compare elements. |
List<E> |
subList(int from,
int to)
Returns a view of the portion of this list between the specified
fromIndex, inclusive, and toIndex, exclusive.
|
Object[] |
toArray()
Returns an array containing all of the elements in this list in proper
sequence (from first to last element).
|
<T> T[] |
toArray(T[] contents)
Returns an array containing all of the elements in this list in
proper sequence (from first to last element); the runtime type of
the returned array is that of the specified array.
|
String |
toString()
Returns a string representation of the object.
|
finalize, getClass, notify, notifyAll, wait, wait, wait
spliterator
parallelStream, removeIf, stream
public CopyOnWriteArrayList()
public CopyOnWriteArrayList(Collection<? extends E> collection)
collection
.public CopyOnWriteArrayList(E[] array)
array
.public Object clone()
Object
x
, the expression:
will be true, and that the expression:x.clone() != x
will bex.clone().getClass() == x.getClass()
true
, but these are not absolute requirements.
While it is typically the case that:
will bex.clone().equals(x)
true
, this is not an absolute requirement.
By convention, the returned object should be obtained by calling
super.clone
. If a class and all of its superclasses (except
Object
) obey this convention, it will be the case that
x.clone().getClass() == x.getClass()
.
By convention, the object returned by this method should be independent
of this object (which is being cloned). To achieve this independence,
it may be necessary to modify one or more fields of the object returned
by super.clone
before returning it. Typically, this means
copying any mutable objects that comprise the internal "deep structure"
of the object being cloned and replacing the references to these
objects with references to the copies. If a class contains only
primitive fields or references to immutable objects, then it is usually
the case that no fields in the object returned by super.clone
need to be modified.
The method clone
for class Object
performs a
specific cloning operation. First, if the class of this object does
not implement the interface Cloneable
, then a
CloneNotSupportedException
is thrown. Note that all arrays
are considered to implement the interface Cloneable
and that
the return type of the clone
method of an array type T[]
is T[]
where T is any reference or primitive type.
Otherwise, this method creates a new instance of the class of this
object and initializes all its fields with exactly the contents of
the corresponding fields of this object, as if by assignment; the
contents of the fields are not themselves cloned. Thus, this method
performs a "shallow copy" of this object, not a "deep copy" operation.
The class Object
does not itself implement the interface
Cloneable
, so calling the clone
method on an object
whose class is Object
will result in throwing an
exception at run time.
public int size()
List
public E get(int index)
List
public boolean contains(Object o)
List
public boolean containsAll(Collection<?> collection)
List
containsAll
in interface Collection<E>
containsAll
in interface List<E>
collection
- collection to be checked for containment in this listList.contains(Object)
public int indexOf(E object, int from)
object
and returns the index of the first
occurrence that is at or after from
.public int indexOf(Object object)
List
public int lastIndexOf(E object, int to)
object
and returns the index of the last
occurrence that is before to
.public int lastIndexOf(Object object)
List
lastIndexOf
in interface List<E>
object
- element to search forpublic boolean isEmpty()
List
public Iterator<E> iterator()
Iterator
that iterates over the elements of this list
as they were at the time of this method call. Changes to the list made
after this method call will not be reflected by the iterator, nor will
they trigger a ConcurrentModificationException
.
The returned iterator does not support Iterator.remove()
.
public ListIterator<E> listIterator(int index)
ListIterator
that iterates over the elements of this
list as they were at the time of this method call. Changes to the list
made after this method call will not be reflected by the iterator, nor
will they trigger a ConcurrentModificationException
.
The returned iterator does not support ListIterator.add(E)
,
ListIterator.set(E)
or Iterator.remove()
,
listIterator
in interface List<E>
index
- index of the first element to be returned from the
list iterator (by a call to next
)public ListIterator<E> listIterator()
listIterator(0)
.listIterator
in interface List<E>
public List<E> subList(int from, int to)
List
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 indexOf and lastIndexOf, and all of the algorithms in the 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.)
public Object[] toArray()
List
The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify the returned array.
This method acts as bridge between array-based and collection-based APIs.
toArray
in interface Collection<E>
toArray
in interface List<E>
Arrays.asList(Object[])
public <T> T[] toArray(T[] contents)
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 list is set to null. (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)
Like the List.toArray()
method, this method acts as bridge between
array-based and collection-based APIs. Further, this method allows
precise control over the runtime type of the output array, and may,
under certain circumstances, be used to save allocation costs.
Suppose x is a list known to contain only strings. The following code can be used to dump the list into a newly allocated array of String:
String[] y = x.toArray(new String[0]);Note that toArray(new Object[0]) is identical in function to toArray().
toArray
in interface Collection<E>
toArray
in interface List<E>
contents
- the array into which the elements of this list are to
be stored, if it is big enough; otherwise, a new array of the
same runtime type is allocated for this purpose.public boolean equals(Object other)
Object
The equals
method implements an equivalence relation
on non-null object references:
x
, x.equals(x)
should return
true
.
x
and y
, x.equals(y)
should return true
if and only if
y.equals(x)
returns true
.
x
, y
, and z
, if
x.equals(y)
returns true
and
y.equals(z)
returns true
, then
x.equals(z)
should return true
.
x
and y
, multiple invocations of
x.equals(y)
consistently return true
or consistently return false
, provided no
information used in equals
comparisons on the
objects is modified.
x
,
x.equals(null)
should return false
.
The equals
method for class Object
implements
the most discriminating possible equivalence relation on objects;
that is, for any non-null reference values x
and
y
, this method returns true
if and only
if x
and y
refer to the same object
(x == y
has the value true
).
Note that it is generally necessary to override the hashCode
method whenever this method is overridden, so as to maintain the
general contract for the hashCode
method, which states
that equal objects must have equal hash codes.
equals
in interface Collection<E>
equals
in interface List<E>
equals
in class Object
other
- the reference object with which to compare.true
if this object is the same as the obj
argument; false
otherwise.Object.hashCode()
,
HashMap
public int hashCode()
Object
HashMap
.
The general contract of hashCode
is:
hashCode
method
must consistently return the same integer, provided no information
used in equals
comparisons on the object is modified.
This integer need not remain consistent from one execution of an
application to another execution of the same application.
equals(Object)
method, then calling the hashCode
method on each of
the two objects must produce the same integer result.
Object.equals(java.lang.Object)
method, then calling the hashCode
method on each of the
two objects must produce distinct integer results. However, the
programmer should be aware that producing distinct integer results
for unequal objects may improve the performance of hash tables.
As much as is reasonably practical, the hashCode method defined by
class Object
does return distinct integers for distinct
objects. (This is typically implemented by converting the internal
address of the object into an integer, but this implementation
technique is not required by the
JavaTM programming language.)
hashCode
in interface Collection<E>
hashCode
in interface List<E>
hashCode
in class Object
Object.equals(java.lang.Object)
,
System.identityHashCode(java.lang.Object)
public String toString()
Object
toString
method returns a string that
"textually represents" this object. The result should
be a concise but informative representation that is easy for a
person to read.
It is recommended that all subclasses override this method.
The toString
method for class Object
returns a string consisting of the name of the class of which the
object is an instance, the at-sign character `@
', and
the unsigned hexadecimal representation of the hash code of the
object. In other words, this method returns a string equal to the
value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
public boolean add(E e)
List
Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.
add
in interface Collection<E>
add
in interface List<E>
e
- element to be appended to this listCollection.add(E)
)public void add(int index, E e)
List
public boolean addAll(Collection<? extends E> collection)
List
addAll
in interface Collection<E>
addAll
in interface List<E>
collection
- collection containing elements to be added to this listList.add(Object)
public boolean addAll(int index, Collection<? extends E> collection)
List
public int addAllAbsent(Collection<? extends E> collection)
collection
that are not already present in
this list. If collection
includes a repeated value, at most one
occurrence of that value will be added to this list. Elements are added
at the end of this list.
Callers of this method may prefer CopyOnWriteArraySet
, whose
API is more appropriate for set operations.
public boolean addIfAbsent(E object)
object
to the end of this list if it is not already present.
Callers of this method may prefer CopyOnWriteArraySet
, whose
API is more appropriate for set operations.
public void clear()
List
public E remove(int index)
List
public boolean remove(Object o)
List
public boolean removeAll(Collection<?> collection)
List
removeAll
in interface Collection<E>
removeAll
in interface List<E>
collection
- collection containing elements to be removed from this listList.remove(Object)
,
List.contains(Object)
public boolean retainAll(Collection<?> collection)
List
retainAll
in interface Collection<E>
retainAll
in interface List<E>
collection
- collection containing elements to be retained in this listList.remove(Object)
,
List.contains(Object)
public void replaceAll(UnaryOperator<E> operator)
List
replaceAll
in interface List<E>
operator
- the operator to apply to each elementpublic void sort(Comparator<? super E> c)
List
Comparator
to compare elements.sort
in interface List<E>
c
- the Comparator
used to compare list elements.
A null
value indicates that the elements'
natural ordering should be usedpublic void forEach(Consumer<? super E> action)
Iterable
Iterable
until all elements have been processed or the action throws an
exception. Unless otherwise specified by the implementing class,
actions are performed in the order of iteration (if an iteration order
is specified). Exceptions thrown by the action are relayed to the
caller.