如何在迭代时从“ ArrayList”中删除元素时如何避免“ ConcurrentModificationException”? [重复]

本文翻译自:How to avoid “ConcurrentModificationException” while removing elements from `ArrayList` while iterating it? [duplicate]

I'm trying to remove some elements from an ArrayList while iterating it like this: 我正在尝试从ArrayList删除一些元素,同时进行如下迭代:

for (String str : myArrayList) {
    if (someCondition) {
        myArrayList.remove(str);
    }
}

Of course, I get a ConcurrentModificationException when trying to remove items from the list at the same time when iterating myArrayList . 当然,当尝试在迭代myArrayList的同时从列表中删除项目时,会收到ConcurrentModificationException Is there some simple solution to solve this problem? 有解决此问题的简单方法吗?


#1楼

参考:https://stackoom.com/question/1FPLD/如何在迭代时从-ArrayList-中删除元素时如何避免-ConcurrentModificationException-重复


#2楼

If you want to modify your List during traversal, then you need to use the Iterator . 如果要在遍历期间修改列表,则需要使用Iterator And then you can use iterator.remove() to remove the elements during traversal. 然后您可以使用iterator.remove()在遍历期间删除元素。


#3楼

Use an Iterator and call remove() : 使用Iterator并调用remove()

Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}

#4楼

You have to use the iterator's remove() method, which means no enhanced for loop: 您必须使用迭代器的remove()方法,这意味着没有增强的for循环:

for (final Iterator iterator = myArrayList.iterator(); iterator.hasNext(); ) {
    iterator.next();
    if (someCondition) {
        iterator.remove();
    }
}

#5楼

As an alternative to everyone else's answers I've always done something like this: 作为其他所有人的答案的替代方案,我总是这样做:

List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
    if (someCondition) {
        toRemove.add(str);
    }
}
myArrayList.removeAll(toRemove);

This will avoid you having to deal with the iterator directly, but requires another list. 这样可以避免您必须直接处理迭代器,但需要另一个列表。 I've always preferred this route for whatever reason. 无论出于什么原因,我总是喜欢这条路线。


#6楼

List myArrayList  = Collections.synchronizedList(new ArrayList());

//add your elements  
 myArrayList.add();
 myArrayList.add();
 myArrayList.add();

synchronized(myArrayList) {
    Iterator i = myArrayList.iterator(); 
     while (i.hasNext()){
         Object  object = i.next();
     }
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章