java UnsupportedOperationException 使用 iterator.remove() 时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28112309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:00:43  来源:igfitidea点击:

UnsupportedOperationException when using iterator.remove()

javaiterator

提问by user3748908

I'm trying to remove some elements from a List, but even the simplest examples, as the ones in this answeror this, won't work.

我正在尝试从 a 中删除一些元素List,但即使是最简单的示例,如this answerthis 中的那些,也不起作用。

public static void main(String[] args)
{
    List<String> list = Arrays.asList("1", "2", "3", "4");
    for (Iterator<String> iter = list.listIterator(); iter.hasNext();)
    {
        String a = iter.next();
        if (true)
        {
            iter.remove();
        }
    }
}

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(Unknown Source)
    at java.util.AbstractList$Itr.remove(Unknown Source)

Using a normal Iteratorinstead of a ListIteratordoesn't help. What am I missing? I'm using java 7.

使用 normalIterator而不是 aListIterator无济于事。我错过了什么?我正在使用 Java 7。

回答by Dima

Arrays.asList()returns a list, backed by the original array. Changes you make to the list are also reflected in the array you pass in. Because you cannot add or remove elements to arrays, that is also impossible to do to lists, created this way, and that is why your removecall fails. You need a different implementation of List(ArrayList, LinkedList, etc.) if you want to be able to add and remove elements to it dynamically.

Arrays.asList()返回一个列表,由原始数组支持。您对列表所做的更改也会反映在您传入的数组中。因为您无法向数组添加或删除元素,所以对以这种方式创建的列表也是不可能的,这就是您的remove调用失败的原因。如果您希望能够动态地向其中添加和删除元素,则需要对List( ArrayListLinkedList等)进行不同的实现。

回答by joey.enfield

This is just a feature of the Arrays.asList() and has been asked before see this question

这只是 Arrays.asList() 的一个特性,在看到这个问题之前已经被问过

You can just wrap this in a new list

您可以将其包装在一个新列表中

List list = new ArrayList(Arrays.asList("1",...));

回答by Laura

Create a new list with the elements you want to remove, and then call removeAllmethode.

使用要删除的元素创建一个新列表,然后调用removeAllmethode。

List<Object> toRemove = new ArrayList<Object>();
for(Object a: list){
    if(true){
        toRemove.add(a);
    }
}
list.removeAll(toRemove);