private static void CopyOnWriteArrayListTest(){
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("test1");
list.add("test2");
list.add("test3");
list.add("test4");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
if ("test1".equals(iterator.next())){
iterator.remove();
}
}
System.out.println(list.toString());
}
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(CopyOnWriteArrayList.java:1178)
CopyOnWriteArrayList
迭代器是只读的,不支持增删操作
CopyOnWriteArrayList
迭代器中的 remove()
和 add()
方法,没有支持增删而是直接抛出了异常。扩展:最全的java面试题库
因为迭代器遍历的仅仅是一个快照,而对快照进行增删改是没有意义的。
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code remove}
* is not supported by this iterator.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code set}
* is not supported by this iterator.
*/
public void set(E e) {
throw new UnsupportedOperationException();
}
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code add}
* is not supported by this iterator.
*/
public void add(E e) {
throw new UnsupportedOperationException();
}