Im playing around with some code for my college course and changed a method from
public boolean removeStudent(String studentName)
{
int index = 0;
f
you can avoid concurrent modification error buy just breaking the loop after removing the element or if the method has a return type return a value after removing the element.
foreach
construct uses an underlying Iterator
.
In the second method you continue to iterate even after removing an item from the list. This is resulting in the exception that you see. Take a look at this statement taken from ConcurrentModificationException
documentation:
For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected.