问题
The Iterator I'm writing is supposed to iterate through all fixed-sized connected subgraphs of another given graph.
As these subgraphs are all very similar (only minor changes in a search-tree based algorithm), I don't want to create a new object to return on each call of next() because of runtime concerns.
Therefore I have an object subGraph that is returned every time, but is changed by a function update() between calls of next(), so that the object works like a view of the current state of the search-tree.
How do I optimally write this iterator, if I want subGraph to remain the same until another call of next()?
From my understanding, I would need to use update() inside of hasNext() to see if the following modification ofsubGraph will be valid. But this would as a side-effect change what you previously got from next(), which is not how hasNext() is supposed to work.
Is the idea of an iterator which always returns the same object a poor design-choice or am I missing something?
来源:https://stackoverflow.com/questions/60961357/java-iterator-is-supposed-to-always-return-the-same-object-but-should-change-i