java.util.Arrays.asList 与 removeIf 一起使用时抛出 UnsupportedOperationException [英] java.util.Arrays.asList when used with removeIf throws UnsupportedOperationException

查看:32
本文介绍了java.util.Arrays.asList 与 removeIf 一起使用时抛出 UnsupportedOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在准备接下来 2 个月的 OCPJP 8 考试目前我这个引起了我的注意,因为我不明白为什么

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

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)

我需要一些帮助来理解为什么 asList 方法不能与 removeIf 一起使用?我假设它将返回一个实现 removeIf 方法的 ArrayList 实例!

I need some help here to understand why the asList method is not working with removeIf? i assume it will return an instance of ArrayList which implements removeIf method!.

任何答案将不胜感激.

干杯!

推荐答案

java.util.Arrays.asList() 生成一个列表,无法从中删除元素,因此它抛出一个删除尝试.

java.util.Arrays.asList() produces a list from which it is impossible to remove elements, so it throws on a removal attempt.

你可以用 ArrayList 包裹它:

List<Integer> ints = new java.util.ArrayList<>(java.util.Arrays.asList(1,20,20));

更新

Arrays.asList() 返回 return new ArrayList<>(a); 其中 ArrayList 不是 java.util.ArrayList,但java.util.Arrays.ArrayList(内部类),不允许删除.

Update

Arrays.asList() returns return new ArrayList<>(a); where ArrayList is not java.util.ArrayList, but java.util.Arrays.ArrayList (internal class), which does not allow removal.

这篇关于java.util.Arrays.asList 与 removeIf 一起使用时抛出 UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆