Main Tutorials

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 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
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Prabhat Kumar
2 years ago

Consumer<List<Integer>> con=list->{
for(int i=0;i<list.size();i++) {
list.add(list.get(i)+1);
}
list.stream().forEach(System.out::println);
};

List<Integer> list=new ArrayList<>(Arrays.asList(1,2,3));
con.accept(list);

Prabhat Kumar
2 years ago
Reply to  Prabhat Kumar

I am getting unsupported error and if I am replacing list.add() to list.set() then there is no issue .

Jose Corpus
4 years ago

Great Answer!