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

Java

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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)

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjavalearnerView Question on Stackoverflow
Solution 1 - JavaEtienne de MartelView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow
Solution 3 - JavahenkoView Answer on Stackoverflow