在调用Arrays.asList(T… a)生成的List的remove方法删除元素时,会报异常:
public static void main(String [] a) {
List<Integer> integers = Arrays.asList(1,2,3,4,5,6);
// remove操作:java.lang.UnsupportedOperationException
integers.removeIf(n -> n < 4);
integers.forEach(System.out::println);
}
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at java.util.AbstractList$Itr.remove(AbstractList.java:374)
at java.util.Collection.removeIf(Collection.java:415)
解决:
使用Arrays.asList(T… a)生成的List做参数重新构造一个java.util.ArrayList即可解决此问题
public static void main(String [] a) {
List<Integer> integers = Arrays.asList(1,2,3,4,5,6);
// 构建一个新的List
List<Integer> newList = new ArrayList<>(integers);
newList.removeIf(n -> n < 4);
newList.forEach(System.out::println);
}
原因:
java.util.Arrays.ArrayList和java.util.ArrayList实现的接口不同.
- java.util.ArrayList实现了java.util.List接口
- java.util.Arrays.ArrayList继承的java.util.AbstractList方法没有实现java.util.List接口中remove方法的逻辑
如下,Arrays中的ArrayList继承了AbstractList
我们进入AbstractList抽象类,查看它的add()和remove()方法
代码中已经很清楚了,直接 throw new UnsupportedOperationException();
版权声明:本文为swadian2008原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。