問題描述
為什么第一個版本的代碼不起作用
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 多次的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!