Calling next on an Iterator once vs multiple times(在迭代器上调用 next 一次 vs 多次)
问题描述
为什么第一个版本的代码不起作用
Why this first version of the code does not work
// returns the longest string in the list (does not work!)
public static String longest(LinkedList<String> list) {
Iterator<String> itr = list.iterator();
String longest = itr.next(); // initialize to first element
while (itr.hasNext()) {
if (itr.next().length() > longest.length()) {
longest = itr.next();
}
}
return longest;
}
但是第二个版本的代码会吗?
but the second version of the code will ?
// this version of the code is correct
while (itr.hasNext()) {
String current = itr.next();
if (current.length() > longest.length()) {
longest = current;
}
}
推荐答案
当你的 if 条件为 true 时,你正在调用 next() 两次:
When your if condition is true, you are calling next() twice:
if (itr.next().length() > longest.length()) {
longest = itr.next();
...
因此,在 if 正文中,您将 next 值的长度(而不是当前值)分配给 longest.
Thus, inside the if body, you are assigning the length of the next value, not the current one, to longest.
Iterator.next() 从集合中返回当前值,但同时将迭代器前进到下一个元素.
Iterator.next() returns the current value from the collection, but at the same time, advances the iterator to the next element.
请注意,如果没有下一个元素,您对 itr.next() 的第二次调用可能会抛出 NoSuchElementException.在您使用 Iterator.hasNext() 检查是否有可用的下一个元素之后,始终只调用 Iterator.next() 一次.
Note that your second call to itr.next() might throw a NoSuchElementException if there is no next element. Always call Iterator.next() only once after you have checked with Iterator.hasNext() whether there is a next element available.
更好的是,使用 foreach 循环来处理样板:
Even better, use the foreach loop which handles all the boilerplate:
for (String current : list) {
....
// "current" now points to the current element
}
这篇关于在迭代器上调用 next 一次 vs 多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在迭代器上调用 next 一次 vs 多次
基础教程推荐
- 将 double 转换为 Int,向下舍入 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- JPA惰性列表上的流 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
