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

前端 未结 5 2065
别跟我提以往
别跟我提以往 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:25

    There isn't much difference between those two methods, other than the first one remembers the value of it after the loop. The second approach probably throws an error, because you redeclare the variable inside the loop.

    There's actually a third method to this, aswell. Instead of writing e.g.

    for (Iterator it = foo.iterator(); it.hasNext();) {
      SomeObject so = foo.next();
    }
    

    you can most often write

    for (SomeObject so: foo) {...}
    

    These two equal to the same thing...

提交回复
热议问题