Java - adding elements to list while iterating over it

前端 未结 5 1778
花落未央
花落未央 2020-12-10 00:53

I want to avoid getting ConcurrentModificationException. How would I do it?

5条回答
  •  感情败类
    2020-12-10 01:53

    You want to use a ListIterator. You can get one of these from any kind of list, though for efficiency you probably want to get one from a LinkedList.

    import java.util.*;
    class TestListIterator {
      public static void main(String[]args) {
        List L = new LinkedList();
        L.add(0);
        L.add(1);
        L.add(2);
        for (ListIterator i = L.listIterator(); i.hasNext(); ) {
          int x = i.next();
          i.add(x + 10);
        }
        System.out.println(L);
      }
    }
    

    Prints [0, 10, 1, 11, 2, 12].

提交回复
热议问题