2013-11-23 108 views
-3

删除项目我写了这个小方法来删除一个阵列中的所有项目具有特定值:对于迭代器阵列

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) 

什么了我错了?我需要改变什么?

+0

首先'如果(文件== R)'是不好的。使用等于比较字符串的内容。第二个谷歌为'ConcurrentModificationException'。 –

+0

您在迭代时删除。改用Iterator.remove()。 –

回答

2

您无法迭代列表并按照您尝试的方式从中删除项目。它导致ConcurrentModificationException。这样做的正确方法,是使用迭代器:

Iterator<String> iterator = notes.iterator(); 
while(iterator.hasNext()) { 
    String file = iterator.next(); 
    if (file == r) 
    iterator.remove(); 
} 

顺便说一句,你可能会想比较字符串时,不==使用equals()

1

在Java 8,这样做:

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