Is it safe to add items to a linked list while iterating?
final LinkedList<Foo> worklist = new LinkedList<>();
Iterator<Foo> iterator = worklist.iterator();
while (iterator.hasNext()) {
Foo foo = iterator.next();
doSomethingWith(foo);
if (expression) {
worklist.add(new Foo());
}
}
If not, how can this behaviour be implemented in a safe and efficient way?
Note that this is not about a list, but specifically about a linked list (it has to be a linked list in my case). And if it isn't safe to do, I'm asking about alternatives.
Aucun commentaire:
Enregistrer un commentaire