Use a for-loop or a for-each loop? [closed]

给你一囗甜甜゛ 提交于 2019-12-06 06:39:30

问题


Should we prefer the for-each loop instead of the traditional for-loops? Is the while-loop advantageous?

List<String> names = Arrays.asList("John", "Jeff", "Mary", "Elise");

//for-each loop
for(String name: names){
    log(name);
}

//traditional for-loop
for(int index=0; index < 10; ++index){
    log(names.get(index));
}

//Iterator while
Iterator<String> iter1 = names.iterator();
while (iter1.hasNext()) {
    log(iter1.next());
}

//Iterator for loop
for(Iterator<String> iter2 = names.iterator(); iter2.hasNext();){
    log(iter2.next());
}

What is the best flavor to use?


回答1:


Are are same. But some case one is more favourable then others

Case 1:

//for-each loop
for(String name: names){
    log(name);
}

Favourable :

  • When you want to iterate over collection
  • no adding or deletion over array.
  • No need of index of item you iterate

Case 2:

//traditional for-loop
for(int index=0; index < 10; ++index){
    log(names.get(index));
}

Favourable :

  • When you want to iterate over collection
  • you need to work on index of item you iterate. So for that you always have value of index you currently on.

Case 3:

Iterator<String> iter1 = names.iterator();
while (iter1.hasNext()) {
    log(iter1.next());
}

and

//Iterator for loop
for(Iterator<String> iter2 = names.iterator(); iter2.hasNext();){
    log(iter2.next());
}

Favourable :

  • When you want to iterate over collection
  • Addition or deletion take ||ly while iterating.



回答2:


Loops 1, 3 and 4 are essentially the same and probably compile to the same bytecode. So use the first one which is more readable.

Loop 2 should be avoided if you don't know what list implementation you are dealing with. In particular, list.get(i) can be an O(n) operation on some lists (LinkedLists for example), making the performance of loop 2 an O(n^2) operation = bad.




回答3:


Options 1 is just a shorten version of 3 and 4. Out of them #1 is preferrable as it easier to write and read. Option 2 may be better in microperformance as it does not create an Iterator object but only in case you use a RandomAccess list like ArrayList




回答4:


Don't use foreach loop when you want to delete some elements inside this loop. Instead use classic for loop, when you can decrease iterator after removing element from collection.




回答5:


For and foreach differ slightly in performance. They are approximately the same speed. But the foreach loop uses more stack space for local variables.

For more detials about this please refer

http://forums.asp.net/t/1209455.aspx/1



回答6:


As long as the container implements Iterable, use for each, as long as mentioned above you do not need an index. Altought probablly you will use the Objects id field instead of a for id.



来源:https://stackoverflow.com/questions/18078354/use-a-for-loop-or-a-for-each-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!