2

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.

  • 2
    What exactly do you want to do here? – Tunaki Oct 20 '15 at 17:44
  • First of all its not clear. But let me tell you one thing you can't modify a list while iterating over it. Only solution to this is to add using iterator. Now clarify more. – SacJn Oct 20 '15 at 17:46
  • You are not really iterating properly in this code snippet. Anyway, perhaps you should tell us what your real task is, so we may suggest an alternative approach. – RealSkeptic Oct 20 '15 at 17:47
  • I'm solving a problem, in wich I need to take a tail of a list and put it front in the same order. For example List: 1, 2, 3, 4, 5 size = 2 List: 4, 5, 1, 2, 3, 4, 5 **QUESTION: How can I iterate and add first element to a LinkedList at the same time?** – Дмитрий Киселев Oct 20 '15 at 18:07

1 Answers1

1

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

Roman Pustylnikov
  • 1,937
  • 1
  • 10
  • 18
  • Thanks! **subList** and **addAll** methods did the job, but List does not support clone method and there is no need for it. `list.addAll(0, list.subList(list.size() - size, list.size()));` – Дмитрий Киселев Oct 21 '15 at 05:30
  • 1
    You're welcome. I looked into it again, you're right, 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). I'll update the answer. – Roman Pustylnikov Oct 21 '15 at 07:49