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?
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 thataddAll
method throws exception because add method forjava.util.Arrays.ArrayList
is defined as:Related question:
Arrays.asList() Confusing source code
From the documentation:
In my case this exception occured when I called
adapter.addAll(items)
, whereadapter
was a customArrayAdapter
. This CustomAdapter had a parameter of typeArray
instead ofArrayList
.This error also happens when the list is initialized with
Collections.emptyList()
, which is immutable:Instead, initialize it with a mutable list. For example
Arrays.asList returns a fixed-size list.
If you to want be able to add elements to the list, do:
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"));