为什么 java.util.Iterator 在嵌套循环中不重置?
Why java.util.Iterator does not reset in a nested loop?
当我运行这段代码时,迭代器iter
在我第二次使用它时是空的。我每次都在外循环中实例化 iter
,但这没有帮助!即第一次迭代后,iterable的长度为零!
为什么会这样?我缺少的这种情况的一般做法是什么?
String path = "somefile.csv";
try {
Reader in = new FileReader(path);
Iterable<CSVRecord> records = CSVFormat.RFC4180.withHeader(MetadataExtractorForTables.HeaderType.class)
.withDelimiter('\t').parse(in);
// A stupid loop
for(int i = 0; i < 3; i++) {
Iterator<CSVRecord> iter = records.iterator();
System.out.println("---> " + Iterators.size(iter));
System.out.println("--> " + StreamSupport.stream(records.spliterator(), false).count());
/* ----------------------------------------
* here I would like to use the iterator
* in a (nested) loop
* ---------------------------------------- */
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
输出如下所示:
---> 191
--> 0
---> 0
--> 0
---> 0
--> 0
因为它是一个邪恶的、违约的 Iterable。
来自docs:
It is not possible to go back, once a record has been parsed from the input stream.
您必须明确地将其复制到列表等中。
当我运行这段代码时,迭代器iter
在我第二次使用它时是空的。我每次都在外循环中实例化 iter
,但这没有帮助!即第一次迭代后,iterable的长度为零!
为什么会这样?我缺少的这种情况的一般做法是什么?
String path = "somefile.csv";
try {
Reader in = new FileReader(path);
Iterable<CSVRecord> records = CSVFormat.RFC4180.withHeader(MetadataExtractorForTables.HeaderType.class)
.withDelimiter('\t').parse(in);
// A stupid loop
for(int i = 0; i < 3; i++) {
Iterator<CSVRecord> iter = records.iterator();
System.out.println("---> " + Iterators.size(iter));
System.out.println("--> " + StreamSupport.stream(records.spliterator(), false).count());
/* ----------------------------------------
* here I would like to use the iterator
* in a (nested) loop
* ---------------------------------------- */
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
输出如下所示:
---> 191
--> 0
---> 0
--> 0
---> 0
--> 0
因为它是一个邪恶的、违约的 Iterable。
来自docs:
It is not possible to go back, once a record has been parsed from the input stream.
您必须明确地将其复制到列表等中。