List.addAll throwing UnsupportedOperationException when trying to add another list
JavaJava Problem Overview
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?
Java Solutions
Solution 1 - Java
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"));
Solution 2 - Java
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<>();
Solution 3 - Java
Arrays.asList returns a fixed-size list.
If you to want be able to add elements to the list, do:
List<String> supportedTypes = new ArrayList<>(Arrays.asList("6500", "7600"});
supportedTypes.addAll(Arrays.asList(supportTypes.split(",")));
Solution 4 - Java
Problem is that Arrays.asList
method returns instance of java.util.Arrays.ArrayList which doesn't support add/remove operations on elements. It's not surprizing that addAll
method throws exception because add method for java.util.Arrays.ArrayList
is defined as:
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
Related question:
https://stackoverflow.com/questions/12015980/arrays-aslist-confusing-source-code
From the documentation:
> Arrays.asList returns a fixed-size list backed by the specified array.
Solution 5 - Java
In my case this exception occured when I called adapter.addAll(items)
, where adapter
was a custom ArrayAdapter
. This CustomAdapter had a parameter of type Array
instead of ArrayList
.