Iterate with for loop or while loop?

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

    There are appropriate uses for the while, the for, and the foreach constructs:

    • while - Use this if you are iterating and the deciding factor for looping or not is based merely on a condition. In this loop construct, keeping an index is only a secondary concern; everything should be based on the condition

    • for - Use this if you are looping and your primary concern is the index of the array/collection/list. It is more useful to use a for if you are most likely to go through all the elements anyway, and in a particular order (e.g., going backwards through a sorted list, for example).

    • foreach - Use this if you merely need to go through your collection regardless of order.

    Obviously there are exceptions to the above, but that's the general rule I use when deciding to use which. That being said I tend to use foreach more often.

提交回复
热议问题