[英]java.util.Arrays.asList when used with removeIf throws UnsupportedOperationException
I am preparing for an OCPJP 8 exam for the next 2 months and currently I this one got my attention as I dont understand why 我准备在接下来的2个月进行OCPJP 8考试,目前我这个考试得到了我的注意,因为我不明白为什么
public class BiPredicateTest {
public static void main(String[] args) {
BiPredicate<List<Integer>, Integer> containsInt = List::contains;
List<Integer> ints = java.util.Arrays.asList(1,20,20);
ints.add(1);
ints.add(20);
ints.add(20);
System.out.println(containsInt.test(ints, 20));
BiConsumer<List<Integer>, Integer> listInt = BiPredicateTest::consumeMe;
listInt.accept(ints, 15);
}
public static void consumeMe(List<Integer> ints, int num) {
ints.removeIf(i -> i>num);
ints.forEach(System.out::println);
}
}
this clearly is going to compile OK! 这显然是编译好的! but when you run it you will see the exception like this
但是当你运行它时,你会看到这样的异常
C:\Users\user\Documents>javac BiPredicateTest.java
C:\Users\user\Documents>java BiPredicateTest
true
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)
at BiPredicateTest.consumeMe(BiPredicateTest.java:22)
at BiPredicateTest.main(BiPredicateTest.java:17)
I need some help here to understand why the asList method is not working with removeIf? 我需要一些帮助来理解为什么asList方法不能与removeIf一起使用? i assume it will return an instance of ArrayList which implements removeIf method!.
我假设它将返回一个实现removeIf方法!的ArrayList实例。
Any answer will be appreciated. 任何答案将不胜感激。
cheers! 干杯!
java.util.Arrays.asList()
produces a list from which it is impossible to remove elements, so it throws on a removal attempt. java.util.Arrays.asList()
生成一个列表,从中无法删除元素,因此它会引发删除尝试。
You could wrap it with ArrayList
: 你可以用
ArrayList
包装它:
List<Integer> ints = new java.util.ArrayList<>(java.util.Arrays.asList(1,20,20));
Arrays.asList()
returns return new ArrayList<>(a);
Arrays.asList()
返回return new ArrayList<>(a);
where ArrayList
is not java.util.ArrayList
, but java.util.Arrays.ArrayList
(internal class), which does not allow removal. 其中
ArrayList
不是java.util.ArrayList
,而是java.util.Arrays.ArrayList
(内部类),它不允许删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.