Java 用于迭代器删除数组中的项

Java 用于迭代器删除数组中的项,java,Java,我编写了这个小方法来删除数组中具有特定值的所有项: public void removeNote2(String r){ for(String file : notes){ if(file == r){ notes.remove(r); } } } 不知怎的,我总是犯这样的错误: java.util.ConcurrentModificationExceptio

我编写了这个小方法来删除数组中具有特定值的所有项:

   public void removeNote2(String r){
         for(String file : notes){
             if(file == r){
                 notes.remove(r);
             }
         }
    }
不知怎的,我总是犯这样的错误:

java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at Notebook.removeNote2(Notebook.java:63)

我做错了什么?我必须改变什么呢?

您不能重复列表并以您尝试的方式从列表中删除项目。它会导致ConcurrentModificationException。正确的方法是使用迭代器:

Iterator<String> iterator = notes.iterator();
while(iterator.hasNext()) {
  String file = iterator.next();
  if (file == r)
    iterator.remove();
}
顺便说一句,在比较字符串时,您可能希望使用等于,而不是==。

在Java 8中,请执行以下操作:

notes.removeIf(file -> file.equals(r));

第一个iffile==r不好。使用equals比较字符串的内容。第二个google for ConcurrentModificationException。您正在迭代时删除。改为使用Iterator.remove。