由 Arrays.asList()创建的 List 上的 move()抛出 Unsupport tedOperationException

我有一个集合 c1<MyClass>和一个数组 a<MyClass>。我试图将数组转换为一个集合 c2和做 c1.removeAll(c2),但这抛出 UnsupportedOperationException。我发现 Array 类的 asList()返回 Arrays.ArrayList类,这个类从 AbstractList()继承 removeAll()AbstractList()的实现抛出 UnsupportedOperationException

    Myclass la[] = getMyClass();
Collection c = Arrays.asList(la);
c.removeAll(thisAllreadyExistingMyClass);

有什么办法可以移除这些元素吗? 请帮帮忙

35838 次浏览

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.

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));

Yup, the Arrays.asList(..) is collection that can't be expanded or shrunk (because it is backed by the original array, and it can't be resized).

If you want to remove elements either create a new ArrayList(Arrays.asList(..) or remove elements directly from the array (that will be less efficient and harder to write)

That is the way Array.asList() works, because it is directly backed by the array. To get a fully modifiable list, you would have to clone the collection into a collection created by yourself.

Collection c = new ArrayList(Arrays.asList(la))