Oliver
Oliver

Reputation: 1043

Java: for loops and Iterators

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
}

Upvotes: 2

Views: 401

Answers (3)

weston
weston

Reputation: 54781

Given that a for loop is just syntactic sugar around a while loop, and you cannot use the "iterating statement" the way you want, it might be neater to use a while loop directly:

Iterator<E> iter = list.iterator();
while (iter.hasNext()) {
  E element = iter.next();
  //some code
}

Upvotes: -1

Bathsheba
Bathsheba

Reputation: 234665

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.)

Upvotes: 6

M A
M A

Reputation: 72844

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.

Upvotes: 6

Related Questions