Generic Collection Methods: forEach and Enhanced for
You'll learn how to iterate over generic collections safely and concently, with automatic type-safe access to each element.
The Core Idea
Now that you have a type-safe ArrayList<E>, you need to loop through its elements. Java provides two elegant ways: the enhanced for loop (also called "for-each") and the forEach method. Both leverage your generic type parameter, so the compiler knows exactly what type each element is—no casting required.
Think of it like a conveyor belt at a bakery: if the belt is labeled "Donuts Only," you don't need to check each item—you know every object coming down is a donut. Generic collections give you that same guarantee.
Enhanced For Loop
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
System.out.println(name.toUpperCase()); // name is guaranteed to be a String
}
The syntax for (String name : names) reads as "for each String name in names." The type String matches your ArrayList<String>, so the compiler ensures type safety.
The forEach Method
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.forEach(num -> System.out.println(num * 2)); // num is inferred as Integer
The forEach method takes code to run on each element. The compiler infers that num is Integer because your collection is ArrayList<Integer>.
Both approaches eliminate manual indexing and casting, making your code cleaner and safer.
Key Takeaway:
Enhanced for loops and the forEach method iterate over generic collections with compile-time type safety, automatically giving you the correct element type without casting.