Purpose and Advantages: The for-each loop simplifies the process of iterating through elements in collections and arrays. It is designed to be more concise and less error-prone than traditional loops, reducing the risk of off-by-one errors and simplifying code.
Supported Data Structures: The for-each loop is primarily used for iterating over arrays and collections (e.g., Lists, Sets, Maps), but it can also be used with any data structure that implements the Iterable interface.
for (elementType element : array) { // Code to be executed for each element }
int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); }
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); for (String name : names) { System.out.println(name); }
You can use the for-each loop with custom objects by implementing the Iterable interface in your class. This allows you to define custom iteration behavior.
=>Avoiding ConcurrentModificationException: When iterating over collections and modifying them within the loop, use an Iterator and its remove() method to avoid concurrency issues. =>Maintaining Code Clarity: Use meaningful variable names for elements to enhance code readability.