'UnsupportedOperationException when trying to remove from the list returned by Array.asList

I am using a List to hold some data obtained by calling Array.asList() method. Then I am trying to remove an element using myList.Remove(int i) method. But while I try to do that I am getting an UnsupportedOperationException. What would be the reason for this? How should I resolve this problem?



Solution 1:[1]

Array.asList() wraps an array in the list interface. The list is still backed by the array. Arrays are a fixed size - they don't support adding or removing elements, so the wrapper can't either.

The docs don't make this as clear as they might, but they do say:

Returns a fixed-size list backed by the specified array.

The "fixed-size" bit should be a hint that you can't add or remove elements :)

Although there are other ways around this (other ways to create a new ArrayList from an array) without extra libraries, I'd personally recommend getting hold of the Google Collections Library (or Guava, when it's released). You can then use:

List<Integer> list = Lists.newArrayList(array);

The reason I'm suggesting this is that the GCL is a generally good thing, and well worth using.

As noted in comments, this takes a copy of the array; the list is not backed by the original array, and changes in either collection will not be seen in the other.

Solution 2:[2]

It's not java.util.ArrayList. Arrays.asList() returns its own List implementation (with changes "written through" to the array.).

It's a fixed-size list so it does not support removal.

You can create a real ArrayList from it:

new java.util.ArrayList<>(Arrays.asList(someArray));  

It's very confusing how asList() works, I must admit.

Solution 3:[3]

Please read the API docs for Arrays.asList():

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

Note that Collections.remove(int) is marked in the Javadocs as an "optional operation", meaning not all Collections will support it. "fixed-size list" means you cannot change the list's size, which remove() would do. So it's not supported.

If you want to change the list generated by Arrays.asList(), just copy it, e.g. new ArrayList(Arrays.asList(...)).

Solution 4:[4]

The implementation you receive from asList doesn't implement a full List interface. I would transform the list to ArrayList and then do modifications on it.

See remove().

Solution 5:[5]

Because you get read-only list. try

List newList = new ArrayList(myList);

Solution 6:[6]

use

ArrayList instead of List

List has fixed size element, List can neither addition item nor remove item

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Pleymor
Solution 3 fospathi
Solution 4 fospathi
Solution 5 St.Shadow
Solution 6 shubomb