java.util.AbstractList.remove 处的 java.lang.UnsupportedOperationException(来源未知)
我已经尝试过下面的代码
String s[]={"1","2","3","4"};
Collection c=Arrays.asList(s);
System.out.println(c.remove("1") +" remove flag");
System.out.println(" collcetion "+c);
,
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
at java.util.AbstractCollection.remove(Unknown Source)
at test.main(test.java:26)
有人可以帮我解决这个问题吗?
I have tried below code
String s[]={"1","2","3","4"};
Collection c=Arrays.asList(s);
System.out.println(c.remove("1") +" remove flag");
System.out.println(" collcetion "+c);
I was getting
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
at java.util.AbstractCollection.remove(Unknown Source)
at test.main(test.java:26)
Can anyone help me to solve this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
简单的解决方法是将 List 传递到 ArrayList 的构造函数中。
例如:
响应:
Easy work around is just to pass in the List into an
ArrayList
's constructor.For example:
Response:
稍微更正:不,它不是一个不可修改的集合。它只是不支持添加和删除元素,因为它由提供的数组支持,并且数组不可调整大小。但它支持类似
list.set(索引, 元素)
Slight correction: no, it's not an unmodifiable Collection. It just doesn't support adding and removing elements, because it is backed by the supplied array and arrays aren't resizeable. But it supports operations like
list.set(index, element)
我遇到了这个问题,因为我也在使用 Arrays.asList 初始化列表:
为了解决这个问题,我使用了
addAll
相反:这样您可以编辑列表、添加新项目或删除。
I was having this problem, because I was also initializing my list with
Arrays.asList
:To solve the problem, I used
addAll
instead:This way you can edit the list, add new items or remove.
java.util.Arrays 类的 Arrays.asList 方法返回的 List 是一个固定大小的列表对象,这意味着不能向列表中添加或删除元素。
因此,诸如添加或删除之类的功能无法在此类列表上进行操作。
添加或删除而不获取
java.lang.UnsupportedOperationException
的解决方案是 ->The List returned by
Arrays.asList
method ofjava.util.Arrays
class is a fixed-size list object which means that elements cannot be added to or removed from the list.So functions like Adding or Removing cannot be operated on such kind of Lists.
The solution to adding or removing without getting
java.lang.UnsupportedOperationException
is ->一个简单的解决办法是像这样声明你的列表:
A one liner fix is to declare your list like this:
以下方法
将打印
注意,
true
是remove()
的(成功)返回值。The following method
Will print
Note that
true
is the (successful) return value fromremove()
.