代码例子
public class Try {
private static List<Integer> list;
public static void main(String[] args) {
list= Arrays.asList(1,2,3);
list.remove(1);
}
}
运行结果:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at other.Try.main(Try.java:18)
原因:
查看源码发现 asList返回的对象是java.util包Arrays类下内部的一个静态类
怎么解决:
将asList转成常规的ArrayList对象,就可以执行成功了
public class Try {
private static List<Integer> list;
public static void main(String[] args) {
list = new ArrayList<>(Arrays.asList(1,2,3));
list.remove(1);
}
}
ArrayList利用动态数组实现了remove(index)方法