从 java 中的 list<String> 中删除一个值会抛出 java.lang.UnsupportedOperationException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10636187/
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
removing a value from a list<String> in java throws java.lang.UnsupportedOperationException
提问by Ashwin
I want to remove specific elements from my List. I don't want to do this while iterating through the list. I want to specify the value which has to be deleted. In javadocs I found the function List.remove(Object 0)
This is my code :
我想从我的列表中删除特定元素。我不想在遍历列表时这样做。我想指定必须删除的值。在 javadocs 中,我找到了函数List.remove(Object 0)
这是我的代码:
String str="1,2,3,4,5,6,7,8,9,10";
String[] stra=str.split(",");
List<String> a=Arrays.asList(stra);
a.remove("2");
a.remove("3");
But I get an Exception : java.lang.UnsupportedOperationException
但我得到一个例外: java.lang.UnsupportedOperationException
回答by NPE
The problem is that Arrays.asList()
returns a list that doesn't support insertion/removal (it's simply a viewonto stra
).
问题是Arrays.asList()
返回一个不支持插入/删除的列表(它只是一个视图到stra
)。
To fix, change:
要修复,请更改:
List<String> a = Arrays.asList(stra);
to:
到:
List<String> a = new ArrayList<String>(Arrays.asList(stra));
This makes a copy of the list, allowing you to modify it.
这会生成列表的副本,允许您对其进行修改。
回答by Eshan Sudharaka
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29
See this. Arrays.asList returns a fixed list. Which is an immutable one. By its definition you cant modify that object once it creates.Thats why it is throwing unsupported exception.
看到这个。Arrays.asList 返回一个固定列表。这是一个不可变的。根据它的定义,一旦它创建,你就不能修改该对象。这就是它抛出不受支持的异常的原因。