use*_*520 2 java exception concurrentmodification
我有一个列表,我需要迭代并删除某些项目.我不能使用迭代器,因为我需要调用每个项目(例如ls.getStatus())的方法,这些方法不适用于迭代器.如果ls.getStatus() == 0我需要删除该项目.我怎么能避免ConcurrentModificationException?
for (MyList ls : list) {
if (ls.getStatus() == 0) {
ls.run();
list.remove();
} else {
ls.create();
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
为什么你认为你不能使用迭代器?
Iterator<MyList> i = list.iterator();
while (i.hasNext()) {
MyList ls = i.next();
//... all your other code which uses ls...
i.remove();
}
Run Code Online (Sandbox Code Playgroud)
这种方法也可能更快,因为使用iterator.remove()避免必须在列表中搜索必要的项目list.remove(item).
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |