Java List java.lang.UnsupportedOperationException

A simple List.add() and hits the following java.lang.UnsupportedOperationException

ListExample.java

package com.mkyong;

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

public class ListExample {

    public static void main(String[] args) {

        List<String> str = Arrays.asList("A", "B", "C");

        str.add("D");

        System.out.println(str);
    }

}

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)
	at com.mkyong.ListExample.main(ListExample.java:14)

Solution

The Arrays.asList returns a fixed-size list, modify is not allowed. To fix it, try this :

ListExample.java

package com.mkyong;

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

public class ListExample {

    public static void main(String[] args) {

        List<String> str = new ArrayList<>(Arrays.asList("A", "B", "C"));
        //List<String> str = Arrays.asList("A", "B", "C");

        str.add("D");

        System.out.println(str);
    }

}

Output


[A, B, C, D]

References

About the Author

author image
mkyong
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

avatar