Skip to content

Most visited

Recently visited

navigation
Added in API level 1

CopyOnWriteArrayList

public class CopyOnWriteArrayList
extends Object implements List<E>, RandomAccess, Cloneable, Serializable

java.lang.Object
   ↳ java.util.concurrent.CopyOnWriteArrayList<E>


A thread-safe random-access list.

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(int, Collection) 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, remove(), add(E) and 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(Collection)).

Summary

Public constructors

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.

Public methods

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)
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(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.

int lastIndexOf(E object, int to)

Searches this list for object and returns the index of the last occurrence that is before to.

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.

ListIterator<E> listIterator()

Equivalent to listIterator(0).

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.

Inherited methods

From class java.lang.Object
From interface java.util.List
From interface java.util.Collection
From interface java.lang.Iterable

Public constructors

CopyOnWriteArrayList

Added in API level 1
CopyOnWriteArrayList ()

Creates a new empty instance.

CopyOnWriteArrayList

Added in API level 1
CopyOnWriteArrayList (Collection<? extends E> collection)

Creates a new instance containing the elements of collection.

Parameters
collection Collection

CopyOnWriteArrayList

Added in API level 1
CopyOnWriteArrayList (E[] array)

Creates a new instance containing the elements of array.

Parameters
array E

Public methods

add

Added in API level 1
boolean add (E e)

Appends the specified element to the end of this list (optional operation).

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.

Parameters
e E: element to be appended to this list
Returns
boolean true (as specified by add(E))

add

Added in API level 1
void add (int index, 
                E e)

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Parameters
index int: index at which the specified element is to be inserted
e E: element to be inserted

addAll

Added in API level 1
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). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it's nonempty.)

Parameters
collection Collection: collection containing elements to be added to this list
Returns
boolean true if this list changed as a result of the call

addAll

Added in API level 1
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). Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in this list in the order that they are returned by the specified collection's iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it's nonempty.)

Parameters
index int: index at which to insert the first element from the specified collection
collection Collection: collection containing elements to be added to this list
Returns
boolean true if this list changed as a result of the call

addAllAbsent

Added in API level 1
int addAllAbsent (Collection<? extends E> collection)

Adds the elements of 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.

Parameters
collection Collection
Returns
int

addIfAbsent

Added in API level 1
boolean addIfAbsent (E object)

Adds 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.

Parameters
object E
Returns
boolean

clear

Added in API level 1
void clear ()

Removes all of the elements from this list (optional operation). The list will be empty after this call returns.

clone

Added in API level 1
Object clone ()

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:

 x.clone() != x
will be true, and that the expression:
 x.clone().getClass() == x.getClass()
will be true, but these are not absolute requirements. While it is typically the case that:
 x.clone().equals(x)
will be 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.

Returns
Object a clone of this instance.

contains

Added in API level 1
boolean contains (Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

Parameters
o Object: element whose presence in this list is to be tested
Returns
boolean true if this list contains the specified element

containsAll

Added in API level 1
boolean containsAll (Collection<?> collection)

Returns true if this list contains all of the elements of the specified collection.

Parameters
collection Collection: collection to be checked for containment in this list
Returns
boolean true if this list contains all of the elements of the specified collection

equals

Added in API level 1
boolean equals (Object other)

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values 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.
  • For any non-null reference value 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.

Parameters
other Object: the reference object with which to compare.
Returns
boolean true if this object is the same as the obj argument; false otherwise.

forEach

Added in API level 24
void forEach (Consumer<? super E> action)

Parameters
action Consumer

get

Added in API level 1
E get (int index)

Returns the element at the specified position in this list.

Parameters
index int: index of the element to return
Returns
E the element at the specified position in this list

hashCode

Added in API level 1
int hashCode ()

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the 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.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the 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.)

Returns
int a hash code value for this object.

indexOf

Added in API level 1
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.

Parameters
object E
from int
Returns
int the index or -1 if the object was not found.

indexOf

Added in API level 1
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. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

Parameters
object Object: element to search for
Returns
int the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element

isEmpty

Added in API level 1
boolean isEmpty ()

Returns true if this list contains no elements.

Returns
boolean true if this list contains no elements

iterator

Added in API level 1
Iterator<E> iterator ()

Returns an 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 remove().

Returns
Iterator<E> an iterator over the elements in this list in proper sequence

lastIndexOf

Added in API level 1
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. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

Parameters
object Object: element to search for
Returns
int the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element

lastIndexOf

Added in API level 1
int lastIndexOf (E object, 
                int to)

Searches this list for object and returns the index of the last occurrence that is before to.

Parameters
object E
to int
Returns
int the index or -1 if the object was not found.

listIterator

Added in API level 1
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. 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 add(E), set(E) or remove(),

Parameters
index int: index of the first element to be returned from the list iterator (by a call to next)
Returns
ListIterator<E> a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list

listIterator

Added in API level 1
ListIterator<E> listIterator ()

Equivalent to listIterator(0).

Returns
ListIterator<E> a list iterator over the elements in this list (in proper sequence)

remove

Added in API level 1
E remove (int index)

Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.

Parameters
index int: the index of the element to be removed
Returns
E the element previously at the specified position

remove

Added in API level 1
boolean remove (Object o)

Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

Parameters
o Object: element to be removed from this list, if present
Returns
boolean true if this list contained the specified element

removeAll

Added in API level 1
boolean removeAll (Collection<?> collection)

Removes from this list all of its elements that are contained in the specified collection (optional operation).

Parameters
collection Collection: collection containing elements to be removed from this list
Returns
boolean true if this list changed as a result of the call

replaceAll

void replaceAll (UnaryOperator<E> operator)

Replaces each element of this list with the result of applying the operator to that element. Errors or runtime exceptions thrown by the operator are relayed to the caller.

Parameters
operator UnaryOperator: the operator to apply to each element

retainAll

Added in API level 1
boolean retainAll (Collection<?> collection)

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

Parameters
collection Collection: collection containing elements to be retained in this list
Returns
boolean true if this list changed as a result of the call

set

Added in API level 1
E set (int index, 
                E e)

Replaces the element at the specified position in this list with the specified element (optional operation).

Parameters
index int: index of the element to replace
e E: element to be stored at the specified position
Returns
E the element previously at the specified position

size

Added in API level 1
int size ()

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Returns
int the number of elements in this list

sort

void sort (Comparator<? super E> c)

Sorts this list using the supplied Comparator to compare elements.

Parameters
c Comparator: the Comparator used to compare list elements. A null value indicates that the elements' natural ordering should be used

subList

Added in API level 1
List<E> subList (int from, 
                int to)

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and 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 supported by this 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.)

Parameters
from int: low endpoint (inclusive) of the subList
to int: high endpoint (exclusive) of the subList
Returns
List<E> a view of the specified range within this list

toArray

Added in API level 1
Object[] toArray ()

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

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.

Returns
Object[] an array containing all of the elements in this list in proper sequence

toArray

Added in API level 1
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. 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 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 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().

Parameters
contents T: 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.
Returns
T[] an array containing the elements of this list

toString

Added in API level 1
String toString ()

Returns a string representation of the object. In general, the 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())
 

Returns
String a string representation of the object.
This site uses cookies to store your preferences for site-specific language and display options.

Hooray!

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.