...

/

ArrayList: Iteration

ArrayList: Iteration

Let's discuss how an ArrayList can be iterated.

Iterating an ArrayList

Below are the different methods to iterate over an ArrayList.

Using for loop

An ArrayList can be iterated easily using a simple for loop or an enhanced for loop as shown below.

Press + to interact
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo {
public static void main(String args[]) {
List <Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
for (int i = 0; i < list.size(); i++) { //Simple for loop
System.out.println(list.get(i));
}
for (Integer i : list) { //Enhanced for loop
System.out.println(i);
}
}
}

Using Iterator

The iterator() method in ArrayList returns an Iterator type object. The Iterator interface declares the below methods that ...