Concurrent Modification exception

前端 未结 9 1361
谎友^
谎友^ 2020-11-22 14:36

I have this little piece of code and it gives me the concurrent modification exception. I cannot understand why I keep getting it, even though I do not see any concurrent mo

9条回答
  •  悲哀的现实
    2020-11-22 15:14

    Have a look at oracle documentation page.

    public class ConcurrentModificationException
    extends RuntimeException
    

    This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible

    Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

    In your case, you have modified the collection after creating the iterator and hence you have encountered the exception.

    If you change your code as per Stephen C answer, you won't get this error.

提交回复
热议问题