简体   繁体   中英

remove() on List created by Arrays.asList() throws 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 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM