代码:
public static void main(String[] args) {
String[] arr ={"a","b","c"};
List<String> list = Arrays.asList(arr);
list.add("d");
list.add("e");
}
运行结果:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:91)
at com.cn.test.main(test.java:11)
修改方法:
List arrayList =new ArrayList(a);
例如:
public static void main(String[] args) {
String[] arr ={"a","b","c"};
List<String> list = Arrays.asList(arr);
List arrList = new ArrayList(list);
arrList.add("d");
arrList.add("e");
}
原因:
在使用Arrays.asList()后调用add,remove这些method时出现java.lang.UnsupportedOperationException异常。这是由于Arrays.asList() 返回java.util.Arrays$ArrayList, 而不是ArrayList。Arrays$ArrayList和ArrayList都是继承AbstractList,remove,add等method在AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。ArrayList override这些method来对list进行操作,但是Arrays$ArrayList没有override remove(),add()等,所以throw UnsupportedOperationException。