Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove() on List created by Arrays.asList() throws UnsupportedOperationException

Tags:

java

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

like image 423
javalearner Avatar asked Oct 25 '11 06:10

javalearner


3 Answers

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));
like image 191
Etienne de Martel Avatar answered Nov 10 '22 04:11

Etienne de Martel


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)

like image 24
Bozho Avatar answered Nov 10 '22 02:11

Bozho


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))
like image 8
henko Avatar answered Nov 10 '22 02:11

henko