做开发一定要注重细节。
在项目中对List进行操作时报错java.lang.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的内部类ArrayList, 而不是java.util.ArrayList。Arrays的内部类ArrayList和java.util.ArrayList都是继承AbstractList,remove、add等方法AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。java.util.ArrayList重新了这些方法而Arrays的内部类ArrayList没有重新,所以会抛出异常。解决方法如下:
-
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");
-
}}