Java - adding elements to list while iterating over it

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

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

相关标签:
5条回答
  • 2020-12-10 01:41

    Create a new list, and populate that one.

    List<MyType> originalList = ...
    List<MyType> newList = new ArrayList<>(originalList);
    
    for(MyType type : originalList)
    {
      // Some decisions
      newList.add(new MyType());
    }
    
    0 讨论(0)
  • 2020-12-10 01:46

    There are three approaches to avoid above exception

    1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.

    2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.

    3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

    0 讨论(0)
  • 2020-12-10 01:50

    Instead of using an iterator, you can use a for loop with an index. For example:

    int originalLength = list.length();
    for (int i = 0; i < originalLength; i++) {
      MyType mt = list.get(i);
      //... processing
      //... insertions
    }
    
    0 讨论(0)
  • 2020-12-10 01:52

    You may use a ListIterator which has support for a remove/add method during the iteration itself.

    ListIterator<Book> iter = books.listIterator();
    while(iter.hasNext()){
        if(iter.next().getIsbn().equals(isbn)){
            iter.add(new Book(...));
        }
    }
    
    0 讨论(0)
  • 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<Integer> L = new LinkedList<Integer>();
        L.add(0);
        L.add(1);
        L.add(2);
        for (ListIterator<Integer> i = L.listIterator(); i.hasNext(); ) {
          int x = i.next();
          i.add(x + 10);
        }
        System.out.println(L);
      }
    }
    

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

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