Iterator Java Example
August 16, 2013
java.util.Iterator iterates the elements in Collection Framework. Iterator has taken the place of Enumeration. Iterator has three elements
1. hasNext()- checks if elements are available.
2. next() - returns the value
3. remove()- removes the elements from the Collection.
Find the example below.
IteratorDemo.java
package com.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratorDemo { public static void main(String[] args) { Listlist = new ArrayList (); list.add("A"); list.add("B"); list.add("C"); System.out.println(list.size()); Iterator itr = list.iterator(); while(itr.hasNext()){ String s = itr.next(); System.out.println(s); if("C".equals(s)){ itr.remove(); } } System.out.println(list.size()); } }
3 A B C 2