I am trying to remove items from my list while iterate, that is why he used Iterator, to later insert emails into a queue. But I get the following error when inserting more elements:
Iterator<String> listCorreos = request.getCorreos().iterator();
while (listCorreos.hasNext()) {
for (Cola cola : colas) {
String correo = listCorreos.next();
cola.insertar(correo);
System.err.println("Se agrego " correo " a la cola: " cola.obtenerNombre());
listCorreos.remove();
}
}
I get the following error
java.util.NoSuchElementException
at java.base/java.util.ArrayList$Itr.next(Unknown Source)
Thank you in advance for any kind of help.
CodePudding user response:
Your problem is that you have two loops and in the second loop you are getting the next element from the object controlling loop 1
See line String correo = listCorreos.next();
while (listCorreos.hasNext()) { // loop 1
for (Cola cola : colas) { // loop 2
String correo = listCorreos.next(); // Here is your problem. the number of colas and the number of items in listCorreos are apparently matched up
cola.insertar(correo);
System.err.println("Se agrego " correo " a la cola: " cola.obtenerNombre());
listCorreos.remove();
}
}
CodePudding user response:
It's not clear what you're trying to do.
But
Iterator<String> listCorreos = request.getCorreos().iterator();
while (listCorreos.hasNext()) {
String correo = listCorreos.next(); //Notice Moved Line!
for (Cola cola : colas) {
cola.insertar(correo);
System.err.println("Se agrego " correo " a la cola: " cola.obtenerNombre());
}
listCorreos.remove();//Also moved.
}
Is probably closer to what you want.
Certainly hasNext() is only "good" for one call to next().
Similarly you can only remove the current item of an iterator once.
But if colas has more than one element you're breaking those constraints.
