Iterate with for loop or while loop?

后端 未结 15 1476
野趣味
野趣味 2020-12-01 13:31

I often see code like:

Iterator i = list.iterator();
while(i.hasNext()) {
    ...
}

but I write that (when Java 1.5 isn\'t available or for

15条回答
  •  再見小時候
    2020-12-01 14:11

    Using for loop you can work with a single variable, as it sets the scope of variable for a current working for loop only. However this is not possible in while loop. For Example:
    int i; for(i=0; in1;i++) do something..

    for(i=0;i n2;i+=2) do something.

    So after 1st loop i=n1-1 at the end. But while using second loop you can set i again to 0. However

    int i=0;

    while(i less than limit) { do something ..; i++; }

    Hence i is set to limit-1 at the end. So you cant use same i in another while loop.

提交回复
热议问题