in the for (int element : collection) loop, the iterator is first called and hasNext + next is called at each step. So why do we check next ?
As you rightly noted, in Java for for each loop:
for (E value : arrayList) { ... }
turns into a for loop using an iterator:
for (Iterator<E> it = arrayList.iterator(); it.hasNext(); ) { E value = it.next(); ... }
Consider the standard implementation of the next() method of the Iterator class in the ArrayList class:
public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
Explicitly, the hasNext() method is not called here, but a check is performed:
if (i >= size)
Why is this check done if in the for each loop before calling the next() method we already checked for the presence of an element by calling the hasNext() method?
In response to this question, I have two suggestions:
It’s trivial: if we use an iterator not by writing a for loop in the style for each , but without it we don’t check the presence of an element (it’s necessary to check, of course, but purely in theory someone could get such an erroneous code):
int i = 0; .... Iterator<Integer> it = arrayList.iterator() while (i < N) { int value = it.next(); ... }
( here it is assumed that arrayList.size() < N ). In this case, the test for the presence of an element in the next() method is justified.
Nonbanal: even in the next() method it is checked whether the collection has been modified or not, but it can be modified after calling checkForComodification(); but before if (i >= size) . In this case, generally speaking, it is unclear what element to give and whether it is necessary at all to give it ( at this point I may not be quite right ).
for (int element : collection)loop, first calls theiteratorand callshasNext+nextat each step. So why do we checknext? - user229269