Issue
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.
Solution
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();
}
}
Answered By - ControlAltDel
Answer Checked By - Mildred Charles (JavaFixing Admin)