remove elements from CopyOnWriteArrayList

2019-02-03 09:35发布

I am getting an exception when I try to remove elements from CopyOnWriteArrayList using an iterator. I have noticed that it is documented

Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.

(from http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html)

Now, surprisingly i can iterate it with foreach and use the remove() function . But then I get the famous bug - when trying to remove an item from a list using a for loop - you skip the element next to the removed element. any suggestions then?

8条回答
神经病院院长
2楼-- · 2019-02-03 10:38

the shortest and most efficient way:

List<String> list = new CopyOnWriteArrayList<>();
list.removeIf(s -> s.length() < 1);

internally it creates an temporary array with the same length and copies all elements where the predicate returns true.

keep in mind that if you use this method to actually iterate over the elements to perform some action, these actions cannot be performed in paralell anymore since the removeIf-call is atomic and will lock the traversal for other threads

查看更多
仙女界的扛把子
3楼-- · 2019-02-03 10:38

Below works fine with CopyOnWriteArrayList

for(String key : list) {
    if (<some condition>) {
        list.remove(key);
    }
}
查看更多
登录 后发表回答