Why am I getting java.util.ConcurrentModificationException?

前端 未结 7 909
独厮守ぢ
独厮守ぢ 2020-12-19 10:55

As I run the following code :

    import java.util.LinkedList;

    class Tester {
      public static void main(String args[]) {
        LinkedList

        
相关标签:
7条回答
  • 2020-12-19 11:47

    The problem is making a change to the list while using an implicit Iterator over it. For the quoted code, the simplest solution is to not use the Iterator at all:

    for(int i=0; i<list.size(); i++) {
      list.add(0,"art");
      list.remove(6);
      System.out.println(list);
    }
    

    You may need to post more realistic code to get advice for the best solution. If you want to possibly remove the current item while iterating over the list, use an explicit Iterator loop, and use the Iterator's remove() method. In other cases, the best solution is to form a plan for the changes inside the loop, but execute it afterwards. For example, during a loop over list build a removeList containing a list of indexes of elements you want to remove. In a separate loop over removeList, remove those elements from list.

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