Good evening. I’m having trouble finding a condition that would stop a loop inside my program. I will try and explain it as generally as possible so the question might help others in the same situation:
I have a collection of objects.
With a piece of code inside the loop, I generate more objects.
I want to add these objects to the collection.
Once they’re added I’d like to iterate over them UNLESS they’ve been iterated over before.
Pseudo-code:
While (!everyObjectHasBeenIteratedOver){
for (Object o : SetOfObjects){
// Generate an unknown number of objects
// Add those objects to the SetOfObjects unless they're already there
}
}
So that’s basically it.
The only answer I know is by using Lists, which support the addition of elements over the iterating list without breaking up, however I, personally, am using HashSets.
Any ideas?
Thanks in advanced.
EDIT: Ended up using a set for the visited objects and another one for the not visited.
Condition: while (!notVisited.isEmpty()) {...}
I propose to use 2 collections: visited and toBeVisited. Visited may be Set and toBeVisited – Queue. So you add new items to queue only if they not visited yet. And when you add item to Queue, you also add it to Set.