如何在没有ConcurrentModificationException的情况下修改subList?

时间:2013-06-01 23:59:17

标签: java iterator linked-list sublist

ListIterator我有点问题。

我已经开始迭代原始列表[1, 4, 5],我在14之间。然后我将列表修改为[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。你知道我怎么能正确地做到这一点?

2 个答案:

答案 0 :(得分:6)

您误解了list.subList的使用情况。

子列表只是原始列表的一部分视图。如果修改子列表,则实际上是在修改原始列表。

你想要的是复制原始列表的一部分:

List<Integer> subList = new ArrayList<Integer>(list.subList(0,2));

答案 1 :(得分:1)

如果您通过迭代器(而不是列表)对列表进行修改,那么您将无法获得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());
相关问题