[英]Weird behaviour of Java iterators
I've encounter a weird problem when using Java iterators. 使用Java迭代器时遇到了一个奇怪的问题。
In a certain function a receive an iterable object called filelist
, and I perform the following : 在某些函数中,将收到一个称为
filelist
的可迭代对象,然后执行以下操作:
System.out.println("First iteration:");
for(Text t : filelist) System.out.println(t);
System.out.println("Second iteration:");
for(Text t : filelist) System.out.println(t);
and the output is: 输出为:
First iteration:
file2.txt
file1.txt
file1.txt
Second iteration:
filelist
is of type Iterable<Text>
. filelist
的类型为Iterable<Text>
。 I'm working with the Hadoop map/reduce framework. 我正在使用Hadoop map / reduce框架。
So my question is, why is file list empty in the second loop, when I didn't change it in the first one? 所以我的问题是,当我在第一个循环中没有更改文件列表时,为什么在第二个循环中文件列表为空?
The Iterable
might return the iterator
that might be non-reiterable. Iterable
可能返回不可iterator
。 Nothing in it's interface says it can't. 它的界面上没有什么说不了。 So in your case it seems that
Iterable
is designed by library authors to be only used once. 因此,在您的情况下,
Iterable
似乎是由库作者设计的,只能使用一次。 If you want to iterate second time, you need to store values in your own structure. 如果要第二次迭代,则需要将值存储在自己的结构中。 Ie you can first do
即您可以先做
List<Text> myList = new ArrayList(filelist)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.