Should we avoid hasNext() call in an Iterator?

iterator, java

Solution

Is it advisable not to use iterator.hasNext() in looping over an iterator?

Um, no. `hasNext` is the standard way you iterate with an iterator. That's what the enhanced-for statement does behind the scenes for an iterable, for example.

Having said that, your code is already ListIterator-specific, as you're using `ListIterator.set` - so your second block of code won't actually compile at the moment. Even if it did, it wouldn't work, as you still need to call `next()`. This would work though:

for (ListIterator<? super T> itr = list.listIterator(); itr.hasNext(); ) {
    itr.next();
    itr.set(obj);
}

Problem

Is it advisable not to use iterator.hasNext() in looping over an iterator? For example I would like to set value obj to each element of a list. I could use the following code or make it more readable by using hasNext() in a loop. ``` int size = list.size(); ListIterator<? super T> itr = list.listIterator(); for (int i=0; i<size; i++) { itr.next(); itr.set(obj); } ``` Instead of these lines I could write my code like the following. ``` for (ListIterator<? super T> itr = list.listIterator(); itr.hasNext(); ) { itr.next(); itr.set(obj); } ```

Original source