java.util.concurrent

Class CopyOnWriteArrayList<E>

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

A thread-safe implementation of an ArrayList. A CopyOnWriteArrayList is as special ArrayList which performs copies of the underlying storage each time a write (remove, add etc..) operation is performed.

The update operation in this class run usually in O(n) or worse, but traversal operations are fast and efficient, especially when running in a multi-thread environment without the need to design complex synchronize mechanisms.

Iterators in this class work on a snapshot of the backing store at the moment the iterator itself was created, hence the iterator will not reflect changes in the underlying storage. Thus, update operation on the Iterators are not supported, but as interferences from other threads are impossible, no ConcurrentModificationException will be ever thrown from within the Iterator.

This class is especially useful when used with event handling, like the following code demonstrates:
 
 CopyOnWriteArrayList listeners =
   new CopyOnWriteArrayList();
 
 [...]
 
 for (final EventListener listener : listeners)
   {
     Runnable dispatcher = new Runnable() {
       public void run()
       {
         listener.preferenceChange(event);
       }
     };
         
     Executor executor = Executors.newSingleThreadExecutor();
     executor.execute(dispatcher);
   }
 

Since: 1.5

Constructor Summary
CopyOnWriteArrayList()
Construct a new ArrayList with the default capacity (16).
CopyOnWriteArrayList(Collection<? extends E> c)
Construct a new ArrayList, and initialize it with the elements in the supplied Collection.
CopyOnWriteArrayList(E[] array)
Construct a new ArrayList, and initialize it with the elements in the supplied array.
Method Summary
booleanadd(E e)
Appends the supplied element to the end of this list.
voidadd(int index, E e)
Adds the supplied element at the specified index, shifting all elements currently at that index or higher one to the right.
booleanaddAll(Collection<? extends E> c)
Add each element in the supplied Collection to this List.
booleanaddAll(int index, Collection<? extends E> c)
Add all elements in the supplied collection, inserting them beginning at the specified index. c can contain objects of any type, as well as null values.
intaddAllAbsent(Collection<? extends E> c)
Adds all the element from the given collection that are not already in this list.
booleanaddIfAbsent(E val)
Adds an element if the list does not contains it already.
voidclear()
Removes all elements from this List
Objectclone()
Creates a shallow copy of this ArrayList (elements are not cloned).
booleancontains(Object e)
Returns true if element is in this ArrayList.
booleancontainsAll(Collection<?> c)
Tests whether this collection contains all the elements in a given collection.
booleanequals(Object o)
Eget(int index)
Retrieves the element at the user-supplied index.
inthashCode()
intindexOf(Object e)
Returns the lowest index at which element appears in this List, or -1 if it does not appear.
intindexOf(E e, int index)
Return the lowest index greater equal index at which e appears in this List, or -1 if it does not appear.
booleanisEmpty()
Checks if the list is empty.
Iterator<E>iterator()
Return an Iterator containing the elements of this list.
intlastIndexOf(Object e)
Returns the highest index at which element appears in this List, or -1 if it does not appear.
intlastIndexOf(E e, int index)
Returns the highest index lesser equal index at which e appears in this List, or -1 if it does not appear.
ListIterator<E>listIterator()
Return a ListIterator containing the elements of this list.
ListIterator<E>listIterator(int index)
Return a ListIterator over the elements of this list starting at the specified index.
Eremove(int index)
Removes the element at the user-supplied index.
booleanremove(Object element)
Remove the first occurrence, if any, of the given object from this list, returning true if the object was removed, false otherwise.
booleanremoveAll(Collection<?> c)
Removes all the elements contained in the given collection.
booleanretainAll(Collection<?> c)
Removes all the elements that are not in the passed collection.
Eset(int index, E e)
Sets the element at the specified index.
intsize()
Returns the number of elements in this list.
List<E>subList(int fromIndex, int toIndex)
Obtain a List view of a subsection of this list, from fromIndex (inclusive) to toIndex (exclusive).
Object[]toArray()
Returns an Object array containing all of the elements in this ArrayList.
<T> T[]toArray(T[] a)
Returns an Array whose component type is the runtime component type of the passed-in Array.
StringtoString()

Constructor Detail

CopyOnWriteArrayList

public CopyOnWriteArrayList()
Construct a new ArrayList with the default capacity (16).

CopyOnWriteArrayList

public CopyOnWriteArrayList(Collection<? extends E> c)
Construct a new ArrayList, and initialize it with the elements in the supplied Collection. The initial capacity is 110% of the Collection's size.

Parameters: c the collection whose elements will initialize this list

Throws: NullPointerException if c is null

CopyOnWriteArrayList

public CopyOnWriteArrayList(E[] array)
Construct a new ArrayList, and initialize it with the elements in the supplied array.

Parameters: array the array used to initialize this list

Throws: NullPointerException if array is null

Method Detail

add

public boolean add(E e)
Appends the supplied element to the end of this list. The element, e, can be an object of any type or null.

Parameters: e the element to be appended to this list

Returns: true, the add will always succeed

add

public void add(int index, E e)
Adds the supplied element at the specified index, shifting all elements currently at that index or higher one to the right. The element, e, can be an object of any type or null.

Parameters: index the index at which the element is being added e the item being added

Throws: IndexOutOfBoundsException if index < 0 || index > size()

addAll

public boolean addAll(Collection<? extends E> c)
Add each element in the supplied Collection to this List. It is undefined what happens if you modify the list while this is taking place; for example, if the collection contains this list. c can contain objects of any type, as well as null values.

Parameters: c a Collection containing elements to be added to this List

Returns: true if the list was modified, in other words c is not empty

Throws: NullPointerException if c is null

addAll

public boolean addAll(int index, Collection<? extends E> c)
Add all elements in the supplied collection, inserting them beginning at the specified index. c can contain objects of any type, as well as null values.

Parameters: index the index at which the elements will be inserted c the Collection containing the elements to be inserted

Throws: IndexOutOfBoundsException if index < 0 || index > 0 NullPointerException if c is null

addAllAbsent

public int addAllAbsent(Collection<? extends E> c)
Adds all the element from the given collection that are not already in this list.

Parameters: c the Collection containing the elements to be inserted

Returns: true the list internal storage changed as a result of this operation, false otherwise.

addIfAbsent

public boolean addIfAbsent(E val)
Adds an element if the list does not contains it already.

Parameters: val the element to add to the list.

Returns: true if the element was added, false otherwise.

clear

public void clear()
Removes all elements from this List

clone

public Object clone()
Creates a shallow copy of this ArrayList (elements are not cloned).

Returns: the cloned object

contains

public boolean contains(Object e)
Returns true if element is in this ArrayList.

Parameters: e the element whose inclusion in the List is being tested

Returns: true if the list contains e

containsAll

public boolean containsAll(Collection<?> c)
Tests whether this collection contains all the elements in a given collection. This implementation iterates over the given collection, testing whether each element is contained in this collection. If any one is not, false is returned. Otherwise true is returned.

Parameters: c the collection to test against

Returns: true if this collection contains all the elements in the given collection

Throws: NullPointerException if the given collection is null

See Also: contains

equals

public boolean equals(Object o)

get

public E get(int index)
Retrieves the element at the user-supplied index.

Parameters: index the index of the element we are fetching

Throws: IndexOutOfBoundsException if index < 0 || index >= size()

hashCode

public int hashCode()

indexOf

public int indexOf(Object e)
Returns the lowest index at which element appears in this List, or -1 if it does not appear.

Parameters: e the element whose inclusion in the List is being tested

Returns: the index where e was found

indexOf

public int indexOf(E e, int index)
Return the lowest index greater equal index at which e appears in this List, or -1 if it does not appear.

Parameters: e the element whose inclusion in the list is being tested index the index at which the search begins

Returns: the index where e was found

isEmpty

public boolean isEmpty()
Checks if the list is empty.

Returns: true if there are no elements

iterator

public Iterator<E> iterator()
Return an Iterator containing the elements of this list. The Iterator uses a snapshot of the state of the internal storage at the moment this method is called and does not support update operations, so no synchronization is needed to traverse the iterator.

Returns: an Iterator containing the elements of this list in sequence.

lastIndexOf

public int lastIndexOf(Object e)
Returns the highest index at which element appears in this List, or -1 if it does not appear.

Parameters: e the element whose inclusion in the List is being tested

Returns: the index where e was found

lastIndexOf

public int lastIndexOf(E e, int index)
Returns the highest index lesser equal index at which e appears in this List, or -1 if it does not appear.

Parameters: e the element whose inclusion in the list is being tested index the index at which the search begins

Returns: the index where e was found

listIterator

public ListIterator<E> listIterator()
Return a ListIterator containing the elements of this list. The Iterator uses a snapshot of the state of the internal storage at the moment this method is called and does not support update operations, so no synchronization is needed to traverse the iterator.

Returns: a ListIterator containing the elements of this list in sequence.

listIterator

public ListIterator<E> listIterator(int index)
Return a ListIterator over the elements of this list starting at the specified index. An initial call to {@code next()} will thus return the element at {@code index}, while an initial call to {@code previous()} will return the element at {@code index-1}. The Iterator uses a snapshot of the state of the internal storage at the moment this method is called and does not support update operations, so no synchronization is needed to traverse the iterator.

Parameters: index the index at which to start iterating.

Returns: a ListIterator containing the elements of this list in sequence.

remove

public E remove(int index)
Removes the element at the user-supplied index.

Parameters: index the index of the element to be removed

Returns: the removed Object

Throws: IndexOutOfBoundsException if index < 0 || index >= size()

remove

public boolean remove(Object element)
Remove the first occurrence, if any, of the given object from this list, returning true if the object was removed, false otherwise.

Parameters: element the object to be removed.

Returns: true if element was removed, false otherwise. false means also that the underlying storage was unchanged after this operation concluded.

removeAll

public boolean removeAll(Collection<?> c)
Removes all the elements contained in the given collection. This method removes the elements that are contained in both this list and in the given collection.

Parameters: c the collection containing the elements to be removed from this list.

Returns: true if at least one element was removed, indicating that the list internal storage changed as a result, false otherwise.

retainAll

public boolean retainAll(Collection<?> c)
Removes all the elements that are not in the passed collection. If the collection is void, this method has the same effect of clear(). Please, note that this method is extremely slow (unless the argument has size == 0) and has bad performance is both space and time usage.

Parameters: c the collection containing the elements to be retained by this list.

Returns: true the list internal storage changed as a result of this operation, false otherwise.

set

public E set(int index, E e)
Sets the element at the specified index. The new element, e, can be an object of any type or null.

Parameters: index the index at which the element is being set e the element to be set

Returns: the element previously at the specified index

Throws: IndexOutOfBoundsException if index < 0 || index >= 0

size

public int size()
Returns the number of elements in this list.

Returns: the list size

subList

public List<E> subList(int fromIndex, int toIndex)
Obtain a List view of a subsection of this list, from fromIndex (inclusive) to toIndex (exclusive). If the two indices are equal, the sublist is empty. The returned list should be modifiable if and only if this list is modifiable. Changes to the returned list should be reflected in this list. If this list is structurally modified in any way other than through the returned list, the result of any subsequent operations on the returned list is undefined.

This implementation returns a subclass of AbstractList. It stores, in private fields, the offset and size of the sublist, and the expected modCount of the backing list. If the backing list implements RandomAccess, the sublist will also.

The subclass's set(int, Object), get(int), add(int, Object), remove(int), addAll(int, Collection) and removeRange(int, int) methods all delegate to the corresponding methods on the backing abstract list, after bounds-checking the index and adjusting for the offset. The addAll(Collection c) method merely returns addAll(size, c). The listIterator(int) method returns a "wrapper object" over a list iterator on the backing list, which is created with the corresponding method on the backing list. The iterator() method merely returns listIterator(), and the size() method merely returns the subclass's size field.

All methods first check to see if the actual modCount of the backing list is equal to its expected value, and throw a ConcurrentModificationException if it is not.

Parameters: fromIndex the index that the returned list should start from (inclusive) toIndex the index that the returned list should go to (exclusive)

Returns: a List backed by a subsection of this list

Throws: IndexOutOfBoundsException if fromIndex < 0 || toIndex > size() IndexOutOfBoundsException if fromIndex > toIndex

See Also: ConcurrentModificationException RandomAccess

toArray

public Object[] toArray()
Returns an Object array containing all of the elements in this ArrayList. The array is independent of this list.

Returns: an array representation of this list

toArray

public <T> T[] toArray(T[] a)
Returns an Array whose component type is the runtime component type of the passed-in Array. The returned Array is populated with all of the elements in this ArrayList. If the passed-in Array is not large enough to store all of the elements in this List, a new Array will be created and returned; if the passed-in Array is larger than the size of this List, then size() index will be set to null.

Parameters: a the passed-in Array

Returns: an array representation of this list

Throws: ArrayStoreException if the runtime type of a does not allow an element in this list NullPointerException if a is null

toString

public String toString()