+91 81900 98289

Java Iterator

An Iterator walks a collection one item at a time. next returns the item. hasNext says whether another item remains. Use iterator.remove if you need to delete the item you just read.

Do not call list.remove inside a for-each over the same list. That throws ConcurrentModificationException. The iterator's own remove is the safe way during a walk.

Example

hasNext is true twice. Each next call returns the next name and moves forward.

import java.util.ArrayList; import java.util.Iterator; public class Walk { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add("Meera"); names.add("Arun"); Iterator<String> it = names.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
Most lesson code can use for-each and stay clearer. Reach for Iterator when the loop must remove items as it goes.