Java 使用ArrayList时如何避免ConcurrentModificationException?

Java 使用ArrayList时如何避免ConcurrentModificationException?,java,android,Java,Android,在Android上使用ArrayList时如何避免ConcurrentModificationException 有人能给出基本的经验法则来避免它吗?在迭代arraylist时不添加/删除元素 当您在迭代时修改列表时,此代码将抛出ConcurrentModificationException List<String> al = new ArrayList<String>(); al.add("2"); for(String s: al) { al.remove("2");

在Android上使用
ArrayList
时如何避免
ConcurrentModificationException


有人能给出基本的经验法则来避免它吗?

在迭代arraylist时不添加/删除元素

当您在迭代时修改列表时,此代码将抛出ConcurrentModificationException

List<String> al = new ArrayList<String>();
al.add("2");
for(String s: al) {
al.remove("2");
}

在迭代ArrayList时,在ArrayList中添加/删除/插入元素时会发生这种情况

错误代码示例:

Iterator it = list.iterator()
while (it.hasNext())
{
    Object o = it.next();
    list.remove(o);
}

如果要删除ArrayList中的元素,请使用迭代器。例如:

ArrayList<String> someStrings;
// fill someStrings
Iterator<String> it = someStrings.iterator();
while(it.hasNext()){
   String buf = it.next();
   // do sth here
}
ArrayList someStrings;
//填充字符串
Iterator it=SomeString.Iterator();
while(it.hasNext()){
字符串buf=it.next();
//在这里做某事
}

你说的是
ConcurrentModificationException
?如果需要良好的帮助,则需要提供问题的确切详细信息。是否使用arraylist方法删除?
Iterator it = list.iterator()
while (it.hasNext())
{
    Object o = it.next();
    list.remove(o);
}
ArrayList<String> someStrings;
// fill someStrings
Iterator<String> it = someStrings.iterator();
while(it.hasNext()){
   String buf = it.next();
   // do sth here
}