-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
  • 5,721
  • 12
  • 49
  • 101

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
  • 20,025
  • 4
  • 51
  • 53
1

In Java 8, do this:

notes.removeIf(file -> file.equals(r));
Stuart Marks
  • 120,620
  • 35
  • 192
  • 252