Java: How to remove elements from a list while iterating over/adding to it

后端 未结 9 1842
谎友^
谎友^ 2020-12-10 11:38

This question is a more special case of the problem described (and solved) in this question.

I have two methods, stopAndRemove(ServerObject server) and a close() met

相关标签:
9条回答
  • 2020-12-10 12:21

    You should get an iterator and remove using it. You are getting the exception because iterators are fail-fast in java.

    0 讨论(0)
  • 2020-12-10 12:22

    You might find this article about ConcurrentModificationException has some advice in this area.

    0 讨论(0)
  • 2020-12-10 12:22

    Answering to the title of the question, not the specific details of the given example. In fact, this solution is not even appropriate in the given situation (refactoring is appropriate, as suggested by others).

    However, it seems that many java programmers are not aware of CopyOnWriteArrayList (part of JDK since 1.5) and are trying to roll their own solutions to the same problem (copy list before iterating).

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