问题描述
我有一个集合 c1
和一个数组 a
.我正在尝试将数组转换为集合 c2
并执行 c1.removeAll(c2)
,但这会引发 UnsupportedOperationException
.我发现 Arrays 类的 asList()
返回 Arrays.ArrayList
类,这个类从 AbstractList 继承了
其实现抛出 removeAll()
()UnsupportedOperationException
.
I have a collection c1<MyClass>
and an array a<MyClass>
. I am trying to convert the array to a collection c2
and do c1.removeAll(c2)
, But this throws UnsupportedOperationException
. I found that the asList()
of Arrays class returns Arrays.ArrayList
class and the this class inherits the removeAll()
from AbstractList()
whose implementation throws UnsupportedOperationException
.
Myclass la[] = getMyClass();
Collection c = Arrays.asList(la);
c.removeAll(thisAllreadyExistingMyClass);
有什么办法可以去除元素吗?请帮忙
Is there any way to remove the elements? please help
推荐答案
Arrays.asList
返回一个围绕数组的 List
包装器.这个包装器有一个固定的大小并直接由数组支持,因此对 set
的调用将修改数组,任何其他修改列表的方法都会抛出一个 UnsupportedOperationException
.
Arrays.asList
returns a List
wrapper around an array. This wrapper has a fixed size and is directly backed by the array, and as such calls to set
will modify the array, and any other method that modifies the list will throw an UnsupportedOperationException
.
要解决此问题,您必须通过复制包装器列表的内容来创建一个新的可修改列表.使用带有 Collection
的 ArrayList
构造函数很容易做到这一点:
To fix this, you have to create a new modifiable list by copying the wrapper list's contents. This is easy to do by using the ArrayList
constructor that takes a Collection
:
Collection c = new ArrayList(Arrays.asList(la));
这篇关于Arrays.asList() 创建的 List 上的 remove() 抛出 UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!