Iterate with for loop or while loop?

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

    Why not use the for-each construct? (I haven't used Java in a while, but this exists in C# and I'm pretty sure Java 1.5 has this too):

    List<String> names = new ArrayList<String>();
    names.add("a");
    names.add("b");
    names.add("c");
    
    for (String name : names)
        System.out.println(name.charAt(0));
    
    0 讨论(0)
  • 2020-12-01 14:08

    I would agree that the "for" loop is clearer and more appropriate when iterating.

    The "while" loop is appropriate for polling, or where the number of loops to meet exit condition will change based on activity inside the loop.

    0 讨论(0)
  • 2020-12-01 14:10

    Not that it probably matters in this case, but Compilers, VMs and CPU's normally have special optimization techniques they user under the hood that will make for loops performance better (and in the near future parallel), in general they don't do that with while loops (because its harder to determine how it's actually going to run). But in most cases code clarity should trump optimization.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 14:13

    if you're only going to use the iterator once and throw it away, the second form is preferred; otherwise you must use the first form

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题