1

So, this returns me

java.util.ConcurrentModificationException

and points to System.out.println line

Iterator<Autor> it = autores.iterator(); 
// Declaring a class iterator

public void listarAutores() {

    while (it.hasNext()) {
        String aux = it.next().getNomeCompleto(); 
        // Get string from Class Autor method
        System.out.println(aux);
        // Printing that string
    }
}

Why it's happening and how can i fix it?

1
  • You probably use the underlying Iterable in the while statement. Commented Dec 12, 2018 at 15:46

2 Answers 2

2

This can happen if you modify the collection between two calls to the method. For example:

listarAutores();
autores.add(anotherAuthor);
listarAutores();

You should create a new iterator in the method at every call or, even better, not use an iterator at all:

public void listarAutores() {
    for (Author a : autores) {
        String aux = a.getNomeCompleto(); 
        // Get string from Class Autor method
        System.out.println(aux);
        // Printing that string
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

or autores.forEach(a -> System.out.println(a.getNomeCompleto()));
The second form may also use an iterator - just an implicit one.
@AndyThomas Yes sure, I meant not explicitly use an iterator.
1

Move your Iterator into the method call. You probably modify the Set somewhere in between.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.