Reputation: 1531
I have a little problem with ListIterator
.
I have started iterate original list [1, 4, 5]
, I am between 1
and 4
. Then I modify list to the [1, 2, 3, 4, 5]
. Now I would like to iterate rest of the original list. Here I give an example code:
public class Test {
public static void main(String[] args) {
List<Integer> list = new LinkedList<Integer>(); // []
list.add(new Integer(1)); // [1]
list.add(new Integer(4)); // [1, 4]
list.add(new Integer(5)); // [1, 4, 5]
ListIterator<Integer> iterator = (ListIterator<Integer>) list.iterator();
System.out.println(iterator.next()); // prints [1]
// modify subList
List<Integer> subList = list.subList(0, 2); // [1, 4]
subList.add(1, new Integer(2)); // [1, 2, 4]
subList.add(2, new Integer(3)); // [1, 2, 3, 4]
// need to print rest of oryginal list: [4, 5]
while (iterator.hasNext())
System.out.println(iterator.next());
}
}
When I'm executing it I have got java.util.ConcurrentModificationException. Do you have any idea how can I do it correctly?
Upvotes: 2
Views: 2787
Reputation: 4878
You've misunderstood the usage of list.subList
.
The sublist is simply a view of a portion of the original list. If you modify the sublist, you're really modifying the original list.
What you want, is to copy part of the original list:
List<Integer> subList = new ArrayList<Integer>(list.subList(0,2));
Upvotes: 7
Reputation: 18148
If you make the modifications to the list through the iterator (instead of through the list) then you won't get a ConcurrentModificationException
System.out.println(iterator.next()); // prints [1]
iterator.add(new Integer(2)); // [1, 2, 4]
iterator.add(new Integer(3)); // [1, 2, 3, 4]
while (iterator.hasNext())
System.out.println(iterator.next());
Upvotes: 1