在Iterator上调用next一次vs多次 [英] Calling next on an Iterator once vs multiple times
问题描述
为什么第一个版本的代码不起作用
//返回列表中最长的字符串(不起作用) !)
public static String longest(LinkedList< String> list){
Iterator< String> itr = list.iterator();
String longest = itr.next(); //初始化为第一个元素
while(itr.hasNext()){
if(itr.next()。length()> longest.length()){
longest = itr.next();
}
}
返回时间最长;
}
但代码的第二个版本会?
//此版本的代码是正确的
而(itr.hasNext()){
String current = itr.next();
if(current.length()> longest.length()){
longest = current;
}
}
你的如果
条件是 true
,你打电话给 next()
两次:
if(itr.next()。length()> longest.length()){
longest = itr.next();
...
因此,在内如果
正文,您将下一个值的长度(而非当前值)分配给最长
。
Iterator.next()
返回集合中的当前值,但同时将迭代器推进到下一个元素。 / p>
请注意,第二次调用 itr.next()
可能会抛出 NoSuchElementException
如果没有下一个元素。在使用 Iterator.hasNext()$ c $进行检查后,始终只能
Iterator.next()
一次 c>是否有下一个元素可用。
更好的是,使用foreach循环:
for(字符串当前:列表){
....
//当前现在指向当前元素
}
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;
}
}
When your if
condition is true
, you are calling next()
twice:
if (itr.next().length() > longest.length()) {
longest = itr.next();
...
Thus, inside the if
body, you are assigning the length of the next value, not the current one, to longest
.
Iterator.next()
returns the current value from the collection, but at the same time, advances the iterator to the next element.
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.
Even better, use the foreach loop which handles all the boilerplate:
for (String current : list) {
....
// "current" now points to the current element
}
这篇关于在Iterator上调用next一次vs多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!