-3

I wrote this little method to delete all items in a array with a specific value:

   public void removeNote2(String r){
         for(String file : notes){
             if(file == r){
                 notes.remove(r);
             }
         }
    }

Somehow i always get this error:

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)

What did i wrong? And what do i have to change?

John Smith
  • 6,105
  • 16
  • 58
  • 109

2 Answers2

2

You cannot iterate the list and remove items from it the way you're trying to do. It leads to ConcurrentModificationException. The proper way to do this, is to use iterator:

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

Btw, you'll probably want to use equals() when comparing strings, not ==.

Andrew Logvinov
  • 21,181
  • 6
  • 52
  • 54
1

In Java 8, do this:

notes.removeIf(file -> file.equals(r));
Stuart Marks
  • 127,867
  • 37
  • 205
  • 259