在java中多次使用同一个集合上的迭代器 [英] Using the iterator over the same set more than once in java

查看:198
本文介绍了在java中多次使用同一个集合上的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在java中迭代一个集合,例如。

Say I'm iterating over a set in java, e.g.

Iterator<_someObject_> it = _someObject_.iterator();

好吧,首先我要浏览集合中的每个对象并对每个对象进行更改访问。所以我使用:

well, first I want to go through every object in the set and make a change to each object I visit. So I use:

while(it.hasNext()) {
        _someObject_ = it.next();
        _someObject_.add3();       //made up method
    }

既然我已经这样做了,我就决定了我希望再次从头到尾遍历整个集合以执行另一个方法,因为我刚刚通过第一次迭代对每个元素进行了更改。

Now that I've done this, I decide I want to iterate through the entire set from start to finish once more to carry out another method on them, given that I've just made changes to each element through my first iteration.

我可以使用

while(it.hasNext())

再次?

我想也许迭代器有一个指针,所以一旦到达最后一个元素第一次运行,如果我再次调用 while(it.hasNext()),指针仍然会在集合的末尾,这意味着我的第二个while循环将是毫无意义。

I thought maybe the iterator has a pointer so once it's reached the last element on the first run through, if I call while(it.hasNext()) again, the pointer would still be at the end of the set, meaning my second while loop would be pointless.

推荐答案

不,你不能这样做。只需向Iterable对象询问另一个迭代器。

No, you can not do this. Just ask the Iterable object for another iterator.

这篇关于在java中多次使用同一个集合上的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆