从CopyOnWriteArrayList中删除元素 [英] remove elements from CopyOnWriteArrayList

查看:576
本文介绍了从CopyOnWriteArrayList中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用迭代器从CopyOnWriteArrayList中删除元素时,我收到异常。
我注意到它已被记录

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


迭代器本身的元素更改操作(删除,设置和添加)不是支持的。这些方法抛出UnsupportedOperationException。

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

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

现在,令人惊讶的是我可以使用foreach迭代它并使用remove()函数。但后来我得到了着名的错误 - 当尝试使用for循环从列表中删除项目时 - 跳过被删除元素旁边的元素。
有什么建议吗?

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?

推荐答案

迭代集合,选择要删除的所有元素并将其放入临时集合中。完成迭代后,使用方法removeAll从原始集合中删除所有找到的元素。

Iterate over the collection choosing all the elements you want to delete and putting those in a temporary collection. After you finish iteration remove all found elements from the original collection using method removeAll.

这对您有用吗?我的意思是,不确定删除逻辑是否比算法中的更复杂。

Would that work out for you? I mean, not sure if deletion logic is more complicated than that in your algorithm.

这篇关于从CopyOnWriteArrayList中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆