public class CopyOnWriteArrayList extends Object implements List, RandomAccess, Cloneable, Serializable
CopyOnWriteArrayList是ArrayList的线程安全变体,其中可以更改ArrayList的操作(添加,更新,设置方法)创建基础数组的克隆。
CopyOnWriteArrayList将在基于线程的环境中使用,在该环境中读取操作非常频繁,而更新操作很少。
CopyOnWriteArrayList的迭代器永远不会抛出ConcurrentModificationException。
自创建迭代器以来,对CopyOnWriteArrayList的任何类型的修改都不会在迭代过程中反映出来。
迭代中不支持列表修改方法,例如remove,set和add。此方法将引发UnsupportedOperationException。
可以将null添加到列表中。
以下是CopyOnWriteArrayList类中可用的重要方法的列表。
| 序号 | 方法与说明 |
|---|---|
| 1 | void add(int index,Object element) 将指定的元素插入此列表中指定位置的索引处。如果指定的索引超出范围(index size()),则抛出IndexOutOfBoundsException 。 |
| 2 | boolean add(Object o) 将指定的元素追加到此列表的末尾。 |
| 3 | boolean addAll(Collection c) 将指定集合中的所有元素按指定集合的迭代器返回的顺序追加到此列表的末尾。如果指定的集合为null,则抛出NullPointerException。 |
| 4 | boolean addAll(int index,Collection c) 从指定位置开始,将指定集合中的所有元素插入此列表。如果指定的集合为null,则抛出NullPointerException。 |
| 5 | voidclear()从此列表中删除所有元素。 |
| 6 | Objectclone()返回此ArrayList的浅表副本。 |
| 7 | boolean contains(Object o) 如果此列表包含指定的元素,则返回true。更正式地说,当且仅当此列表包含至少一个元素(e == null?e == null:o.equals(e))时,返回true。 |
| 8 | Object get(int index) 返回此列表中指定位置的元素。如果指定的索引超出范围(index = size()),则抛出IndexOutOfBoundsException 。 |
| 9 | int indexOf(Object o) 返回指定元素首次出现在此列表中的索引;如果List不包含此元素,则返回-1。 |
| 10 | int lastIndexOf(Object o) 返回指定元素最后一次出现在此列表中的索引;如果列表不包含此元素,则返回-1。 |
| 11 | Object remove(int index) 移除此列表中指定位置的元素。如果索引超出范围(index = size()),则抛出IndexOutOfBoundsException 。 |
| 12 | Object set(int index,Object element) 用指定的元素替换此列表中指定位置的元素。如果指定的索引超出范围(index = size()),则抛出IndexOutOfBoundsException 。 |
| 13 | intsize()返回此列表中的元素数。 |
| 14 | Object []toArray()返回以正确顺序包含此列表中所有元素的数组。如果指定的数组为null,则抛出NullPointerException。 |
以下程序说明了ArrayList支持的几种方法-
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class Tester {
public static void main(String args[]) {
//创建一个数组列表
CopyOnWriteArrayList al = new CopyOnWriteArrayList();
System.out.println("Initial size of al: " + al.size());
//将元素添加到数组列表
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
//显示数组列表
System.out.println("Contents of al: " + al);
//从数组列表中删除元素
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
try {
Iterator iterator = al.iterator();
while(iterator.hasNext()) {
iterator.remove();
}
}catch(UnsupportedOperationException e) {
System.out.println("不支持的方法:");
}
System.out.println("Size of al: " + al.size());
}
}这将产生以下结果-
Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D] 不支持的方法: Size of al: 5