Search code examples
javalistlinked-listiteratorconcurrentmodification

java iterate list and addFirst at the same time


When I try to do

ListIterator<Integer> iter = list.listIterator(list.size());

for (int i = 0; i < size; i++) {
     iter.hasPrevious();
     list.addFirst(iter.previous());
}

I get ConcurrentModificationException. I know what that means, but how can I add first element to a List and iterate it at the same time? Execution time and memory limit are crucial.


Solution

  • Well, since you know the size of the list and therefore the first index to copy - you can either get the subList clone and use addAll(0,..) or use get(index++) and addFirst(..) methods.

    Note that iterating on sublist directly while adding might lead to the same issue since subList returns only view of original list. See http://docs.oracle.com/javase/7/docs/api/java/util/List.html#subList(int,%20int)

    However, it's OK to modify the original list as long as the changes are not structural to the subList view (do not affect size or iteration ability).