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.
Iterator in Java Example
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.
- hasNext() Method:-The hasNext() method returns true if the iteration has many elements.
- next() method:- The next () method returns the next element in the iteration.
- remove() method:- The remove method removes the last element returned by the iterator from the underlying collection. We can call this method only once.
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: