Difference between moving an Iterator forward with a for statement and a while statement

前端 未结 5 2066
别跟我提以往
别跟我提以往 2021-01-11 10:16

When I use an Iterator of Object I use a while loop (as written in every book learning Java, as Thinking in Java of Bruce Eckel):

I         


        
5条回答
  •  终归单人心
    2021-01-11 10:31

    The correct syntax for the for loop is:

    for (Iterator it = ...; it.hasNext(); ){
        //...
    }
    

    (The preceding declaration in your code is superfluous, as well as the extra semicolon in the for loop heading.)

    Whether you use this syntax or the while loop is a matter of taste, both translate to exactly the same. The generic syntax of the for loop is:

    for (; ; ) { ; }
    

    which is equivalent to:

    ;
    while () { ; ; }
    

    Edit: Actually, the above two forms are not entirely equivalent, if (as in the question) the variable is declared with the init statement. In this case, there will be a difference in the scope of the iterator variable. With the for loop, the scope is limited to the loop itself, in the case of the while loop, however, the scope extends to the end of the enclosing block (no big surprise, since the declaration is outside the loop).

    Also, as others have pointed out, in newer versions of Java, there is a shorthand notation for the for loop:

    for (Iterator it = myIterable.iterator(); it.hasNext(); ) {
        Foo foo = it.next();
        //...
    }
    

    can be written as:

    for (Foo foo : myIterable) {
        //...
    }
    

    With this form, you of course lose the direct reference to the iterator, which is necessary, for example, if you want to delete items from the collection while iterating.

提交回复
热议问题