Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

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

0 contributions
14 points

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

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more