Exception in thread "main" java.lang.Unsupportedoperationexception

Asked

Viewed 538 times

2

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

When trying to use the method removeIf(), to test on a list that receives a Predicate, I’m having the exception quoted in the title, someone knows 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 so it print 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 of the exception thrown, when I pass the users inside the :

Arrays.asList();

2 answers

3


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

To documentation calls it the "bridge between collections and arrays Apis". The reason for this behavior is probably that they thought it important to have the property that the same vector passed to the function composed the data from the generated list. Performance issue, I imagine. It’s a good justification, but this name causes a lot of confusion.

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

  • In the case Arrays.asList is imutavel ? and Arraylist<>() not ?

  • 2

    It is not immutable, but cannot change size (you can change the value of the elements). ArrayList is a List "normal", which allows removal normally.

  • Thanks understand man, thanks for the force!

-1

If you need to use Arrays.asList() anyway, then you can do it this way to avoid the error. List list = new Arraylist(Arrays.asList())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.