使用iterator.remove()时UnsupportedOperationException [英] UnsupportedOperationException when using iterator.remove()
问题描述
我正在尝试从 List
中删除一些元素,但即使是最简单的示例,也可以在此答案或此将无效。
I'm trying to remove some elements from a List
, but even the simplest examples, as the ones in this answer or this, won't work.
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)
使用正常 Iterator
而不是 ListIterator
没有帮助。
我缺少什么?我正在使用java 7.
Using a normal Iterator
instead of a ListIterator
doesn't help.
What am I missing? I'm using java 7.
推荐答案
Arrays.asList()
返回由原始数组支持的列表。您对列表所做的更改也会反映在您传入的数组中。由于您无法向数组添加或删除元素,因此也无法对列表进行此操作,这就是您的删除
调用失败。
你需要一个不同的 List
的实现( ArrayList
, LinkedList
等)如果你想能够动态地添加和删除元素。
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 remove
call 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.
这篇关于使用iterator.remove()时UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!