Iterator Java


Iterator Java Example – Explanation – Screenshot

Iteration is nothing but repeating the same operation multiple times. For this, every language, including Java, gives a control structure for loop. Especially for iterating the data structure elements, Java gives three special loops – Enumeration, Iterator and ListIterator. All the three are meant to iterate only; but they do the job with little variations and extra operations.

Let us write a small example on Iterator Java and then explain.
import java.util.*;
public class PrintElements
{
 public static void main(String args[])
 {
   ArrayList al = new ArrayList();
   al.add("Jyostna");
   al.add(100);
   al.add(10.5);
   al.add(new Date());

   Iterator it = al.iterator();

   System.out.println("ArrayList Elements:");
   
   while(it.hasNext())
   {
     System.out.println(it.next());
   }
 }
}


Iterator Java
Output Screenshot on Iterator Java

An ArrayList object al is created and added elements with add() method. iterator() method of ArrayList returns an object of Iterator interface containing all the elements of ArrayList. hasNext() method of Iterator iterate each element and next() method returns each element.

Fore more command over iterators, how they differ from each other, extra features added in ListIterator etc. are clear discussed in the following links of this same Web site.

Enumeration Iterator
ListIterator Arrays foreach
Collections foreach Enumeration vs Iterator
Iterator vs ListIterator

Leave a Comment

Your email address will not be published.