Java 对于每个,但多个迭代器类型?
我有一个 Polygon 类,我希望在其上实现两个迭代器:一个迭代器仅运行一次所有元素(按交替顺序的顶点和边),另一个迭代器无限地(循环)运行它们。
从 for-each 用法的角度来看,我的猜测是,通过实现 Iterable.iterator()<,我只能将上述之一作为可与 for-each 一起使用的默认迭代器。 /代码>。这是正确的吗?或者有没有一种方法可以将 for-each 与两者一起使用?
I have a class Polygon
on which I wish to implement two iterators: one to run through all elements (vertices and edges in alternating order) just ONCE, and another to run through them ad infinitum (cyclically).
From a for-each usage standpoint, my guess is that I am only going to be able to have one of the above be the default iterator that can be used with for-each, via implementation of Iterable.iterator()
. Is this correct? Or is there a way I could use for-each with both?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需添加两个返回两个不同迭代器的方法,每个迭代器对应一种情况:
这只是一个字符串列表的示例,只需适应即可。
而不是
仅仅使用
或循环版本
Just add two methods returning two different Iterators, one for each case:
This is just an example with a List of Strings, just adapt.
Instead of
just use
or the cyclic edition
我认为比已经提出的答案更好的答案是一种将任何 Iterable 转换为循环的方法。
然后,您可以在 Polygon 类中实现单个迭代器方法,并使用
迭代一次和
for (Element e: Cycle(polygon)) {
...
}
无限迭代。作为奖励,循环修饰符可以应用于任何可迭代对象。
An answer I think is better than those already presented is a method that turns any Iterable into a cyclic one.
Then you can just implement the single iterator method in the Polygon class and use
to iterate once and
for (Element e: cycle(polygon)) {
...
}
to iterate endlessly. As a bonus, the cycle modifier can be applied to any iterable.