+ 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?

29th Nov 2016, 2:59 AM
Ankit Sanghavi
Ankit Sanghavi - avatar
2 Respostas
+ 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
29th Nov 2016, 3:53 AM
Eric Gitangu
Eric Gitangu - avatar
+ 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
29th Nov 2016, 3:17 AM
Allan Navarro
Allan Navarro - avatar