I’m looking to make a recursive method iterative.
I have a list of Objects I want to iterate over, and then check their subobjects.
Recursive:
doFunction(Object) while(iterator.hasNext()) { //doStuff doFunction(Object.subObjects); }
I want to change it to something like this
doFunction(Object) iIterator = hashSet.iterator(); while(Iterator.hasNext() { //doStuff hashSet.addAll(Object.subObjects); }
Sorry for the poor psuedo code, but basically I want to iterate over subobjects while appending new objects to the end of the list to check.
I could do this using a list, and do something like
while(list.size() > 0) { //doStuff list.addAll(Object.subObjects); }
But I would really like to not add duplicate subObjects. Of course I could just check whether list.contains(each subObject) before I added It.
But I would love to use a Set to accomplish that cleaner.
So Basically is there anyway to append to a set while Iterating over it, or is there an easier way to make a List act like a set rather than manually checking .contains()?
Any comments are appreciated.
Thanks
I would use two data structures — a queue (e.g.
ArrayDeque) for storing objects whose subobjects are to be visited, and a set (e.g.HashSet) for storing all visited objects without duplication.NOTES:
ArrayDequeis a space-efficient queue. It is implemented as a cyclic array, which means you use less space than aListthat keeps growing when you add elements.boolean fresh = visited.add(o)‘ combines ‘boolean fresh = !visited.contains(o)‘ and ‘if (fresh) visited.add(o)‘.