Languages
[Edit]
EN

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

14 points
Created by:
Kate_C
19790

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

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join