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.