Java: Iterator is supposed to always return the same object, but should change it between calls of next()

邮差的信 提交于 2021-01-29 09:36:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!