+ 2
Java For Loop - There are three ways for iterating list elements using For loop. Which one is recommended?
In Java, I can iterate the list elements using below three ways using for loop. 1. for (int i = 0; i < list.size(); i++) { Person p = list.get(i); ... } 2. for(Person p : list) { ... } 3. for (Iterator<Person> it: list.iterator(); it.hasNext(); ) { Person p = it.next(); ... } Which is the most efficient / recommend?
2 Respuestas
+ 2
depends, for granular access an iterator Is best but if you intend to use all items in your list them a for each statement is best, the first approach is commonly used for random access
+ 1
in this case for lists I would use
for(Person p: list)
it guarantees including all elements and is easier to understand.
i don't know in terms of efficiency