[英]java.lang.UnsupportedOperationException at java.util.AbstractList.remove(Unknown Source)
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?谁能帮我解决这个问题?
Easy work around is just to pass in the List into an ArrayList
's constructor. 简单的解决方法就是将List传递给
ArrayList
的构造函数。
For example: 例如:
String valuesInArray[]={"1","2","3","4"}; List modifiableList = new ArrayList(Arrays.asList(valuesInArray)); System.out.println(modifiableList.remove("1") + " remove flag"); System.out.println(" collcetion "+ modifiableList);
Response: 响应:
true remove flag
真正删除标志
collcetion [2, 3, 4]
collcetion [2,3,4]
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)
但它支持
list.set(index, element)
I was having this problem, because I was also initializing my list with Arrays.asList
: 我遇到了这个问题,因为我还用
Arrays.asList
初始化我的列表:
List<String> names = Arrays.asList("a", "b", "c");
To solve the problem, I used addAll
instead: 为了解决这个问题,我使用了
addAll
:
List<String> names = new ArrayList<String>();
names.addAll(Arrays.asList("a", "b", "c"));
This way you can edit the list, add new items or remove. 这样您就可以编辑列表,添加新项目或删除。
The List returned by Arrays.asList
method of java.util.Arrays
class is a fixed-size list object which means that elements cannot be added to or removed from the list. 由
java.util.Arrays
类的Arrays.asList
方法返回的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 -> 在不获取
java.lang.UnsupportedOperationException
情况下添加或删除的解决方案是 - >
List<String> strList= new ArrayList<>(Arrays.asList(strs));
//Then Add or Remove can be called on such List
newList.add("100");
newList.remove("100");
一个衬线修复方法是像这样声明您的列表:
List<Integer> list2 = new ArrayList<>(Arrays.asList(0,8,1,5,7,0));
The following method下面的方法
private void printCollection() {
List<String> strings = new ArrayList<>(Arrays.asList("1", "2", "3", "4"));
System.out.println(strings.remove("1") + " remove flag");
System.out.println("collection " + strings);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.