I want to avoid getting ConcurrentModificationException. How would I do it?
- 
        docs.oracle.com/javase/6/docs/api/java/util/concurrent/…kosa– kosa2012-07-24 04:44:39 +00:00Commented Jul 24, 2012 at 4:44
- 
        its my mistake, before we provide you solution, you should provide code where you are getting exceptiondeveloper– developer2012-07-24 05:17:45 +00:00Commented Jul 24, 2012 at 5:17
- 
        possible duplicate of Java: adding elements to a collection during iterationoers– oers2012-07-24 12:52:19 +00:00Commented Jul 24, 2012 at 12:52
5 Answers
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(...));
    }
}
1 Comment
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
}
4 Comments
get(i) you will have to visit all the nodes until you reach the node i. Not a good approach IMHO.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].
Comments
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());
}
3 Comments
There are three approaches to avoid above exception
- 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. 
- 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. 
- If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach. 
3 Comments
ConcurrentModificationException. This exception happens in single-threaded code. Am I missing something?