Main Tutorials

Java List throws UnsupportedOperationException

Typically, we use Arrays.asList or the new Java 9 List.of to create a List. However, both methods return a fixed size or immutable List, it means we can’t modify it, else it throws UnsupportedOperationException.

JavaListExample.java

package com.mkyong;

import java.util.Arrays;
import java.util.List;

public class JavaListExample {

    public static void main(String[] args) {

        // immutable list, cant modify, java.util.Arrays$ArrayList
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        // immutable list, cant modify , java 9
        List<Integer> list2 = List.of(1, 2, 3, 4, 5);

        //list.add(6); // UnsupportedOperationException
        list.add(6);   // UnsupportedOperationException

    }
}

Output


Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractList.add(AbstractList.java:153)
	at java.base/java.util.AbstractList.add(AbstractList.java:111)

Solution

If we want to create a mutable list, that allows us to modify it, create an ArrayList.

JavaListExample.java

package com.mkyong;

import java.util.ArrayList;
import java.util.List;

public class JavaListExample {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        list.add(6); // modify the list

        list.forEach(System.out::println);

    }

}

Output


1
2
3
4
5
6

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments