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?
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.
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.
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).
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.
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"));
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<>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With