Ways to iterate over a list in Java

后端 未结 12 1918
孤独总比滥情好
孤独总比滥情好 2020-11-22 00:46

Being somewhat new to the Java language I\'m trying to familiarize myself with all the ways (or at least the non-pathological ones) that one might iterate through a list (or

12条回答
  •  粉色の甜心
    2020-11-22 01:14

    You could always switch out the first and third examples with a while loop and a little more code. This gives you the advantage of being able to use the do-while:

    int i = 0;
    do{
     E element = list.get(i);
     i++;
    }
    while (i < list.size());
    

    Of course, this kind of thing might cause a NullPointerException if the list.size() returns 0, becuase it always gets executed at least once. This can be fixed by testing if element is null before using its attributes / methods tho. Still, it's a lot simpler and easier to use the for loop

提交回复
热议问题