我有一個小問題ListIterator
。如何修改沒有ConcurrentModificationException的子列表?
我已經開始迭代原始列表[1, 4, 5]
,我在1
和4
之間。然後我修改列表[1, 2, 3, 4, 5]
。現在我想重複其餘的原始列表。這裏給出一個示例代碼:
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());
}
}
當我執行它時,我得到java.util.ConcurrentModificationException。你有什麼想法,我該如何正確地做到這一點?
,而你遍歷它不能修改的東西。你將不得不復制修改和遍歷原始文件。 – Colleen