Iterate with for loop or while loop?

后端 未结 15 1450
野趣味
野趣味 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:19

    I think scope is the biggest issue here, as you have pointed out.

    In the "while" example, the iterator is declared outside the loop, so it will continue to exist after the loop is done. This may cause issues if this same iterator is used again at some later point. E. g. you may forget to initialize it before using it in another loop.

    In the "for" example, the iterator is declared inside the loop, so its scope is limited to the loop. If you try to use it after the loop, you will get a compiler error.

提交回复
热议问题