Java.util.Arrays.asList when used with removeIf throws UnsupportedOperationException

I am preparing for the OCPJP 8 exam over the next 2 months and currently I have received this attention because I do not 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 is clearly going to compile OK! but when you run it, you will see an 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 help here to understand why the asList method does not work with removeIf? I assume that it will return an ArrayList instance that implements the removeIf! Method.

Any answer would be appreciated.

Hooray!

+11
source share
1 answer

java.util.Arrays.asList() creates a list from which it is impossible to delete items, so it generates an attempt to delete.

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 ( ), .

+19

Source: https://habr.com/ru/post/1673198/


All Articles