如何制作一个永不结束的迭代器?
我只是想知道无限期地迭代集合的最简单方法是什么,即当它到达末尾时,它 next();
调用第一个对象。 我假设这不是 Java 中预定义的函数,所以只是寻找在 Java 中实现它的最简单方法。
I was just wondering what the easiest way to iterate over a set indefinitely, i.e. when it reaches the end it next();
calls the first object. I'm assuming that this is not an already predefined function in Java, so just looking for the easiest way to implement this in Java.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
优秀的 Google Collections 库中有一个方法可以执行此操作:(
我不推荐 Google Collections 库因为我在 Google 工作,所以它非常有偏见,但我认为几乎每个编写 Java 的 Google 员工都会告诉您这些集合有多么有用。)
There's a method in the excellent Google Collections library which does this:
(I can't recommend the Google Collections library strongly enough. It rocks very hard. I'm biased as I work for Google, but I think pretty much every Googler writing Java would tell you how useful the collections are.)
尝试
EndlessIterator
< /a> 来自 Cactoos:它将始终返回
"John"
并且永远不会结束。另外,检查
EndlessIterable
,它实现了Iterable
并执行相同的操作。Try
EndlessIterator
from Cactoos:It will always return
"John"
and will never end.Also, check
EndlessIterable
, which implementsIterable
and does the same.如果您正在创建迭代器,则在下一个方法中您可以使用 if 条件来检查列表中是否有另一个对象。 如果有,则返回该对象,如果没有,则返回到列表的开头并返回该对象。
If you're making the iterator, in the next method you can have an if condition that checks if there's another object in the list. If there is, then you return that object, if there isn't then you go back to the start of the list and return that object.
这是我能想到的...
This is what I can think of...
怎么样 ?
How about ?
如果您不想使用 Guava 但仍想要一个可重用的解决方案:
注意:这不支持 remove() 方法,但如果需要,可以轻松添加。 而且它也不是线程安全的。
If you don't want to use Guava but still want a reusable solution:
Note: this doesn't support the remove() method but it could easily be added if needed. Also it's not thread safe.
我认为你想要的永远不会有帮助你可以用你的迭代器做任何事情,这很简单,但是你必须小心你添加的任何新东西,我不使用这种风格,但这就是你想要的:
if (! It.hasNext() )
{
while ( It.hasPrevious() )
{
它 = It.Previous();
}
} 别的 {
它 = It.Next();
如果
您真的感兴趣,这种方法没什么用,您应该在推送新列表时始终将最后一个指针指向第一个。
I think what you want never help You can do anything with your iterator that's easy but you must be carefull with any new thing you add im not used with this style but this is what you want though :
if (! It.hasNext() )
{
while ( It.hasPrevious() )
{
It = It.Previous();
}
} else {
It = It.Next();
}
This way is nothing if your really interested you should instead make next pointer of the last to the first always when pushing a new list.
标准jdk:
std jdk: