Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.addAll throwing UnsupportedOperationException when trying to add another list [duplicate]

Tags:

java

List.addAll throwing UnsupportedOperationException when trying to add another list.

List<String> supportedTypes = Arrays.asList("6500", "7600"}; 

and in loop I am doing,

supportedTypes.addAll(Arrays.asList(supportTypes.split(","))); //line 2 

reading supportTypes from a file.

But line 2 throws a UnsupportedOperationException, but I am not able to determine why?

I am adding another list to a list, then why this operation is unsupported?

like image 508
codingenious Avatar asked Sep 02 '14 13:09

codingenious


People also ask

How do I stop UnsupportedOperationException?

How to Resolve 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 is difference between ADD () and addAll () methods?

add is used when you need to add single element into collection. addAll is used when you want to add all elements from source collection to your collection.

What does list addAll do in Java?

addAll(int index, Collection<? extends E> c) method inserts all of the elements in the specified collection into this list, starting at the specified position. It shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices).

What does addAll method do?

The addAll() method of java. util. Collections class is used to add all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array.


2 Answers

Arrays.asList returns a fixed sized list backed by an array, and you can't add elements to it.

You can create a modifiable list to make addAll work :

List<String> supportedTypes = new ArrayList<String>(Arrays.asList("6500", "7600", "8700"));

like image 186
Eran Avatar answered Oct 21 '22 03:10

Eran


This error also happens when the list is initialized with Collections.emptyList(), which is immutable:

List<String> myList = Collections.emptyList(); 

Instead, initialize it with a mutable list. For example

List<String> myList = new ArrayList<>(); 
like image 41
Suragch Avatar answered Oct 21 '22 04:10

Suragch