1. Introduction
Iterating over elements of a collection is a common operation in programming. In Java, the ArrayList class, part of the java.util package, provides several methods to iterate through the elements. In this example, we will showcase how to use different techniques such as the for-each loop, Iterator, and ListIterator to iterate over an ArrayList.
2. Program Steps
1. Initialize an ArrayList and populate it with some elements.
2. Iterate through the ArrayList using the for-each loop and print each element.
3. Iterate through the ArrayList using an Iterator and print each element.
4. Iterate through the ArrayList using a ListIterator and print each element.
3. Code Program
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListIteration {
public static void main(String[] args) {
// Step 1: Initialize an ArrayList and populate it with some elements
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Iterate through the ArrayList using for-each loop and print each element
System.out.println("Iterating using for-each loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Step 3: Iterate through the ArrayList using Iterator and print each element
System.out.println("Iterating using Iterator:");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Step 4: Iterate through the ArrayList using ListIterator and print each element
System.out.println("Iterating using ListIterator:");
ListIterator<String> listIterator = fruits.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
}
}
Output:
Iterating using for-each loop: Apple Banana Cherry Iterating using Iterator: Apple Banana Cherry Iterating using ListIterator: Apple Banana Cherry
4. Step By Step Explanation
Step 1: We initialize an ArrayList named fruits and populate it with the strings "Apple", "Banana", and "Cherry".
Step 2: We use a for-each loop to iterate over each element of the ArrayList and print it. The for-each loop is a concise way to iterate over all elements of a collection.
Step 3: We obtain an Iterator for the ArrayList and use the hasNext() and next() methods of the Iterator interface to iterate over each element of the list and print it.
Step 4: Similarly, we obtain a ListIterator for the ArrayList and use the hasNext() and next() methods of the ListIterator interface to iterate over each element of the list and print it. The ListIterator provides additional functionality, such as iterating in reverse order, which is not covered in this example.