Iterator
An Iterator is an object used to go through the elements of a collection one by one, in a standard way, regardless of the specific type of collection being used (List, Set, or Map's key/value views).
1. What is an Iterator?
An Iterator is an object used to go through the elements of a collection one by one, in a standard way, regardless of the specific type of collection being used (List, Set, or Map's key/value views).
2. Why is it used?
It provides a consistent, safe way to loop through any collection's elements, and it also allows safely removing elements while iterating — something a normal for loop can't do reliably on collections.
3. Real-Life Example
Think of flipping through pages of a photo album one at a time, always moving forward, and being able to remove a photo you're currently looking at without disturbing the rest of the album. An Iterator provides this same controlled, one-by-one movement through a collection.
4. Syntax
javaIterator<DataType> it = collectionName.iterator(); while (it.hasNext()) { DataType value = it.next(); }
5. Example Program
javaimport java.util.ArrayList; import java.util.Iterator; public class IteratorDemo { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); Iterator<String> it = fruits.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
Output:
Apple
Banana6. Key Points to Remember
hasNext()checks if more elements exist;next()retrieves the next element.Iteratoralso provides aremove()method to safely delete the current element during iteration.- Directly modifying a collection while using a regular for-each loop (instead of an Iterator's
remove()) can cause aConcurrentModificationException.