Languages
[Edit]
EN

Java - Arrays.asList() add new element throws java.lang.UnsupportedOperationException FIX

14 points
Created by:
Brett4
435

1. FIXED - by using ArrayList constructor

Instead of using:

List<String> list = Arrays.asList(arr);

Use:

List<String> list = new ArrayList<>(Arrays.asList(arr));

Example:

String[] arr = {"Tim", "Jerry", "Ann"};

// FIXED:
List<String> list = new ArrayList<>(Arrays.asList(arr));

list.add("TEST");

// [Tim, Jerry, Ann]
System.out.println(list.toString());


2. Reproduction and explanation:

String[] arr = {"Tim", "Jerry", "Ann"};
List<String> list = Arrays.asList(arr);

// below method throws java.lang.UnsupportedOperationException
list.add("TEST");

Stack trace:

java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
Java docs of Arrays.asList:
Returns a fixed-size list backed by the specified array.

As we can see from stack trace when we call list.add method we call it on custom implementation of ArrayList.
This implementation is a part of java core class: java.util.Arrays
This custom implementation doesn't implement add method, that's why we get this exception.

Java docs of List.add:
Throws:
UnsupportedOperationException - if the add operation is not supported by this list


3. Other ways to convert array to list

Java - create list from array

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join