-1

这是我的代码:

public class Test {
    public static void main(String[] args){
        ArrayList<Integer> list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(2);
        list.add(2);
        list.add(5);
        int inteval = 0;
        Iterator<Integer> it = list.iterator();
        for(;it.hasNext();){
            Integer n = it.next();
            list.remove(n);
            if (list.contains(n-inteval)){
                list.remove(list.indexOf(n-inteval));
                if (list.contains(n-inteval-inteval)){
                    list.remove(list.indexOf(n-inteval-inteval));
                }else{
                    list.add(n-inteval);
                    list.add(n);
                }
            }
        }
    }
}

此代码将抛出 ConcurrentModificationException,我曾尝试使用 CopyOnWriteArrayList,但我发现它。next() 返回上次删除的值!我该如何解决?

4

2 回答 2

0

这是因为您正在执行以下操作:

    Iterator<Integer> it = list.iterator();
    for(;it.hasNext();){
        Integer n = it.next();
        list.remove(n);

使用 时Iterator,不能listlist.remove(),list.add()函数修改 。要使用迭代器删除元素,您需要调用it.remove(),它会删除您使用 获得的元素it.next()。如果您真的想这样做,那么您应该执行以下操作:

    for(int i = 0; i < list.size(); i++){
        Integer n = list.get(i);
    ...

尽管您还需要确保当您修改列表并且元素被来回推送时,您只检查一个元素一次。您可能更容易使用您需要的元素构建一个不同的列表。

于 2014-09-15T08:47:47.917 回答
0

使用任何列表方法获取迭代器后,您不应修改列表。

正如已经指出的 - 在 Iterator 实例上调用 remove 方法。

例如 -

public class Test {
    public static void main (String... at) throws Exception {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(2);
        list.add(2);
        list.add(5);

        Iterator<Integer> it = list.iterator();
        //below while will remove every element from the list
        while (it.hasNext()) {
            it.next();
            it.remove();
        }
        //this will leave 5 as the only element in list
        /*while (it.hasNext()) {
            if (it.next() != 5) {
                it.remove();
            }
        }*/
        //below loop will remove all the occurences of 1 or 2
        while (it.hasNext()) {
            Integer number = it.next();
            if (number == 1 || number == 2) {
                it.remove();
            }
        }
        System.out.println(list.toString());
    }
}
于 2014-09-15T09:41:40.937 回答