Java Concurrent Modification Exception Error

后端 未结 8 1758
庸人自扰
庸人自扰 2020-12-11 03:50

Im playing around with some code for my college course and changed a method from

public boolean removeStudent(String studentName)
{
    int index = 0;
    f         


        
相关标签:
8条回答
  • 2020-12-11 04:23

    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.

    0 讨论(0)
  • 2020-12-11 04:30

    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.

    0 讨论(0)
提交回复
热议问题