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
}