Iterate with for loop or while loop?

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

    Although both are really fine, I tend to use the first example because it is easier to read.

    There are fewer operations happening on each line with the while() loop, making the code easier for someone new to the code to understand what's going on.

    That type of construct also allows me to group initializations in a common location (at the top of the method) which also simplifies commenting for me, and conceptualization for someone reading it for the first time.

提交回复
热议问题