Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - adding elements to list while iterating over it

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

like image 933
Trup Avatar asked Jul 24 '12 04:07

Trup


People also ask

Can you add to list while iterating Java?

You can use ListLterator for modifying list during iterating,it provides more functionality than iterator.

Can we add elements using iterator?

The add() method of ListIterator interface is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by next() method.

What happens if you modify the value of an element in a list while iterating using iterators?

The size of the List is not being changed, but the object at the index is changing, so technically the List is being modified.


3 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(...));     } } 
like image 194
Edwin Dalorzo Avatar answered Oct 11 '22 17:10

Edwin Dalorzo


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 } 
like image 28
JimN Avatar answered Oct 11 '22 17:10

JimN


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].

like image 42
Keith Randall Avatar answered Oct 11 '22 19:10

Keith Randall