Java Reference
In-Depth Information
Listing 12-3 contains the complete program that shows how to use the for-each loop to iterate over elements of a
list of strings. The program is simple and self-explanatory.
Listing 12-3. Using a for-each Loop to Iterate Over Elements of a List
// ForEachLoop.java
package com.jdojo.collections;
import java.util.ArrayList;
import java.util.List;
public class ForEachLoop {
public static void main(String[] args) {
// Create a list of strings
List<String> names = new ArrayList<>();
// Add some names to the list
names.add("Ken");
names.add("Lee");
names.add("Joe");
// Print all elements of the names list
for(String name : names) {
System.out.println(name);
}
}
}
Ken
Lee
Joe
The for-each loop is not a replacement for using an iterator. The compactness of the for-each loop wins over
using an iterator in most use cases. The for-each loop has several limitations, however.
You cannot use the for-each loop everywhere you can use an iterator. For example, you cannot use
the for-each loop to remove elements from the collection. The following snippet of code will throw a
ConcurrentModificationException exception:
List<String> names = get a list;
for(String name : names) {
// Throws a ConcurrentModificationException
names.remove(name);
}
Another limitation of the for-each loop is that you must traverse from the first element to the last element of the
collection. It provides no way to start from middle of the collection. The for-each loop provides no way to visit the
previously visited elements, which is allowed by the iterator of some collection types such as lists.
Search WWH ::




Custom Search