UnsupportedOperationException

UnsupportedOperationException

本文介绍了由Arrays.asList()创建的List上的remove()抛出UnsupportedOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 c1< MyClass> 的集合和一个数组 a< MyClass> 。我试图将数组转换为集合 c2 并执行 c1.removeAll(c2),但这会抛出 UnsupportedOperationException异常。我发现Arrays类的 asList()返回 Arrays.ArrayList 类,这个类继承了 removeAll()来自 AbstractList(),其实现抛出 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.

要解决此问题,您必须通过复制包装列表的内容来创建新的可修改列表。使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 05:43