Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 415
Chathuranga Chandrasekara Avatar asked Oct 26 '09 10:10

Chathuranga Chandrasekara


People also ask

How do I get rid of UnsupportedOperationException?

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.

What does arrays asList () do?

The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.

What type of list does arrays asList return?

asList returns a fixed-size list that is​ backed by the specified array; the returned list is serializable and allows random access.

Can you modify the collection return by arrays asList ()?

Using Arrays. Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it.


2 Answers

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.

like image 98
Jon Skeet Avatar answered Sep 23 '22 09:09

Jon Skeet


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.

like image 24
Carlos Avatar answered Sep 22 '22 09:09

Carlos