我正在为接下来的两个月准备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);
}
}
这段代码显然是可以编译通过的!但是当你运行它时,你会看到如下异常:
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)
我需要一些帮助来理解为什么asList方法与removeIf无法正常工作?我认为它会返回一个实现removeIf方法的ArrayList实例!
感谢任何回答。
更新:2022年4月16日 即使使用java.util.Arrays.asList,错误也不再发生,我注意到:
- 最新的Java 1.8 *实现不再使用内部的ArrayList类,而是使用java.util包下的类。
- List接口现在也有默认实现。