Exception in thread "main" java.lang.UnsupportedOperationException

2

Predicate is a functional interface that allows you to test objects of a given type. Given Predicate , removeIf will remove all elements which return true for this predicate.

When trying to use the removeIf() method, to test a list that receives a Predicate, I'm having the exception quoted in the title, does anyone know why?

Code:

Predicate<Usuario> predicado = new Predicate<Usuario>() {
        public boolean test(Usuario u) {
            return u.getPontos() > 160;
        }
};


List<Usuario> lista = Arrays.asList(usuario,usuario1, usuario2, usuario3);
lista.removeIf(predicado);
lista.forEach(u -> System.out.println(u));

But when I do this, it prints without error:

Predicate<Usuario> predicado = new Predicate<Usuario>() {
    public boolean test(Usuario u) {
        return u.getPontos() > 160;
    }
};

List<Usuario> lista = new ArrayList<Usuario>();


lista.add(usuario2);
lista.add(usuario3);
lista.add(usuario1);
lista.add(usuario);
lista.removeIf(predicado);
lista.forEach(u -> System.out.println(u));

Does anyone know why the exception thrown, when I pass the users inside:

Arrays.asList();
    
asked by anonymous 30.03.2016 / 18:39

1 answer

1

The problem is that Arrays.asList returns a fixed-length list. You are trying to modify this list, so you get the exception.

documentation calls this "bridge between collections and array APIs". The reason for this behavior is probably that they found it important to have the property that the same vector passed to the function made up the data from the generated list. Performance issue, I imagine. It's a good excuse, but that name causes a lot of confusion.

Java has no problem calling a class of BufferedInputStream but did not call this method of wrapInAList or something like that. You will understand ...

    
30.03.2016 / 20:21