We are going to discuss about iterator in java. Iterator is an interface in the collection framework and it works similar to the Enumeration. The java iterator traverse through all the elements of the collection. We have used three method hasNext() and next(). and remove() method. However we can also use while loop and for loop.
We are going to discuss about iterator in java. Iterator is an interface in the collection framework and it works similar to the Enumeration. The java iterator traverse through all the elements of the collection. We have used three method hasNext() and next(). and remove() method. However we can also use while loop and for loop.We are going to discuss about iterator in java. Iterator is an interface in the collection framework and it works similar to the Enumeration. The java iterator traverse through all the elements of the collection. We have used three method hasNext() and next(). and remove() method. However we can also use while loop and for loop.
In this example, we have used hasNext() and next() method.
Example
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class SimpleTest { public static void main(String[] args) { Listlist = new ArrayList (); list.add("Apple"); list.add("Banana"); list.add("Orange"); list.add("Apricot"); list.add("Carrot"); useWhileLoop(list); useForLoop(list); } private static void useWhileLoop(Collection aFlavours) { Iterator Iter = aFlavours.iterator(); while (Iter.hasNext()) { System.out.println(Iter.next()); } } // Note that this for-loop does not use an integer index. private static void useForLoop(Collection aFlavours) { for (Iterator Iter = aFlavours.iterator(); Iter.hasNext();) { System.out.println(Iter.next()); } } }
OutPut:
Ads