List是不能使用remove()的,

看以下代码:

1
2
3
4
5
6
String [] a = new String[4];
a[0] = "1";
a[1] = "2";
List<String> list = Arrays.asList(a);
list.remove(0);
System.out.println(list.get(0));

这是会报错的:

Exception in thread “main” java.lang.UnsupportedOperationException

at java.util.AbstractList.remove(AbstractList.java:172)
at com.nevol.list.ListTest.main(ListTest.java:27)

很明显是不支持的操作!

查看源码(AbstractList.java:172)

1
2
3
public E remove(int index) {
throw new UnsupportedOperationException();
}

没有逻辑,直接抛出UnsupportedOperationException

解决方法,只要将List转成ArrayList就可以了,具体代码如下

1
2
3
4
5
6
7
String [] a = new String[4];
a[0] = "1";
a[1] = "2";
List<String> list = Arrays.asList(a);
list = new ArrayList<String>(list);
list.remove(0);
System.out.println(list.get(0));