Reputation: 11
If the size of list is known, only call the 'next' without 'hasNext'. Is it right?
final List<Integer> list = [1, 2, 3];
final Iterator<Integer> iter = list.iterator();
for(int i = 0; i < list.size(); ++i){
System.out.println(iter.next());
}
Upvotes: 1
Views: 1201
Reputation: 14025
Yes, that's allowed. In your example, there isn't much point to it (you'd be better off either using list.get(i)
or using hasNext()
/next()
), but it doesn't break anything.
One place where you do see next()
without hasNext()
is to get an arbitrary item out of a collection that is known not to be empty. This idiom comes up sometimes:
Collection<T> myCollection = ...;
if (!myCollection.isEmpty()) {
return myCollection.iterator().next();
}
Upvotes: 3
Reputation: 7917
If there is no next element and you still call next()
, you'll get NoSuchElementException
. To protect against this, you need to do a pre-check using hasNext()
.
In your example, you already know the size and the condition i < list.size()
is guarding you against trying to jump after the last element, so there is no point calling hasNext()
.
We generally do:
while (iterator.hasNext()) { //protection against jumping after the last element
//call next()
}
You have done a similar thing, just the "protection" is a bit different (but valid):
for(... i < list.size() ...) { //"i < list.size()" is providing that protection
//call next()
}
So no need to use hasNext()
here.
Upvotes: 3