UnsupportedOperationException while removing or adding elements to a List

+1 vote
32 views
asked Feb 27 by Hitesh Garg (132 points)  

I have created a list from Arrays.asList and while manipulating that list I am getting UnsupportedOperationException, both at list.add() and list.remove() methods.
What is the problem with the code and how to fix this?

final Long[] arr = {1.0L, 2.0L};
List myNewList = Arrays.asList(someArrayOfLong);

myNewList.add(new Long(3)); //add an element in the list.
myNewList.remove(0); //remove element from the list at index 0.

1 Answer

+1 vote
answered Feb 27 by Rahul Singh (163 points)  

This happens because Arrays.asList returns an immutable list, which is non modifiable and according to official documentation -

Returns a fixed-size list backed by the specified array. (Changes to
the returned list “write through” to the array.) This method acts as
bridge between array-based and collection-based APIs, in combination
with Collection#toArray. The returned list is serializable and
implements RandomAccess.

For more details look at this detailed post on how to convert an array to a List

Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...