Every For Loop with an Iterator that i've ever used (to use the Iterator.remove(); method) looks like this:
for (Iterator<E> iter = list.iterator(); iter.hasNext(); ) {
E element = iter.next();
//some code
}
Basic For Loops are styled:
for([initial statement]; [loop condition]; [iterating statement]) {/*Some Code*/}
So my question is... why are they never written
for (Iterator<E> iter = list.iterator(); iter.hasNext(); E element = iter.next()) {
//some code
}
The iterating statement executes after the loop body has executed. In other words, when you write the following:
for (Iterator<E> iter = list.iterator(); iter.hasNext(); element = iter.next()) {
//some code
}
element = iter.next() would run after the body has run for each iteration, so if you are printing the element, for example, the first element would be whatever initial value element had.
Example:
List<String> list = new ArrayList<String>();
list.add("a1");
list.add("a2");
list.add("a3");
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String string = iterator.next();
System.out.println(string);
}
Output:
a1
a2
a3
With the iter.next() in the for loop:
List<String> list = new ArrayList<String>();
list.add("a1");
list.add("a2");
list.add("a3");
String string = null;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); string = iterator.next()) {
System.out.println(string);
}
Output:
null
a1
a2
P.S.: The loop as you declared (for (Iterator<E> iter = list.iterator(); iter.hasNext(); E element = iter.next()) will not compile, so you would need to declare element as a variable before this line.
The for loop grammar does not permit you to declare a variable in the "iterating statement".
(You can declare one in the "initial statement" which is why for (Iterator<E> iter = list.iterator(); iter.hasNext(); ) is syntatically valid.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With