Why this first version of the code does not work
// returns the longest string in the list (does not work!)
public static String longest
Count the number of times next()
is called in the first snipped compared to the second:
while (itr.hasNext()) {
if (itr.next().length() > longest.length()) {
^^^^^^^^^^
longest = itr.next();
^^^^^^^^^^
}
}
compared to
while (itr.hasNext()) {
String current = itr.next();
^^^^^^^^^^
if (current.length() > longest.length()) {
longest = current;
}
}
Every time you call itr.next()
, you advance the iterator another token. So in the first snippet, you only store/compare every other token, while in the second snippet you store/compare the same token.