Java List java.lang.UnsupportedOperationException
By:Roy.LiuLast updated:2019-08-11
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]
From:一号门
Previous:Java two-dimensional array example
COMMENTS