美文网首页
java.lang.UnsupportedOperationEx

java.lang.UnsupportedOperationEx

作者: Qin0821 | 来源:发表于2018-08-13 18:15 被阅读0次

UnsupportedOperationException往往发生在对由数组转换而成的list的操作中。
例如:

public class ListTest {
    public static void main(String[] args) {
        String[] array = {"1","2","3","4","5"};
        List<String> list = Arrays.asList(array);
        list.add("6");
    }
}

执行结果:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at com.atguigu.test.ListTest.main(ListTest.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

发生的原因如下:
调用Arrays.asList()产生的list的add、remove方法时,编译器会发现Arrays.asList()返回的是Arrays的内部类,而不是java.util.ArrayList.虽然它两都是集成AbstractList,但是remove、add等方法在AbstractList中是默认throw UnsupportedOperationException的。

解决方案:

public class ListTest {
    public static void main(String[] args) {
        String[] array = {"1","2","3","4","5"};
        List<String> list = Arrays.asList(array);
        List arrList = new ArrayList(list);
        arrList.add("6");
    }
}

参考链接

相关文章

网友评论

      本文标题:java.lang.UnsupportedOperationEx

      本文链接:https://www.haomeiwen.com/subject/qhbicftx.html