Here we will use Iterator to iterate through the elements of ArrayList object in Java.
Source Code
package com.beginner.examples;
import java.util.ArrayList;
import java.util.Iterator;
public class GetIteratorExample {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(4);
al.add(5);
Iterator iterator = al.iterator();
//This iterator can only remove elements
while(iterator.hasNext())
{
Integer element = iterator.next();
iterator.remove();
System.out.println(element);
}
System.out.println("Remove all:----->"+al);
}
}
Output:
1
2
3
4
5
Remove all:----->[]
References
Imported packages in Java documentation: