Languages
[Edit]
EN

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

14 points
Created by:
Kate_C
2860

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

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.