You must use Iterator to remove the entry from your list. If you try to change your List when iterating through the extended for loop, it may throw a ConcurrentModificationException , although this does not always happen, but there is no guarantee.
Here you can use Iterator for your list: -
Iterator<Entry> iterator = Directory.entries.iterator(); while (iterator.hasNext()) { Entry entry = iterator.next(); if (entry.name.equalsIgnoreCase(nameToDelete)) { iterator.remove(); } }
Even in Iterator you must remove the element using the iterator.remove method, and not using the list.remove method, because it will not matter.
You can also use ListIterator , which gives you even more operations and methods for iterating over the list. See the documentation for more details.
To use ListIterator , you can create it like this: -
ListIterator<Entry> listIterator = Directory.entries.listIterator();
And the rest of the code works the same way.
source share