我对 ListIterator
有点问题。
我已经开始迭代原始列表[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。你知道我怎样才能正确地做到这一点吗?
最佳答案
您误解了 list.subList
的用法.
子列表只是原始列表的一部分的 View 。如果您修改子列表,您实际上是在修改原始列表。
你想要的是复制原始列表的一部分:
List<Integer> subList = new ArrayList<Integer>(list.subList(0,2));
关于java - 如何在没有 ConcurrentModificationException 的情况下修改 subList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16878460/