Set Iterator Java

Set 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 comes with three special loops given by three interfaces – Enumeration, Iterator and ListIterator. All the three are meant to iterate only; but they do the job with little variations and extra operations.

Before going into the example, I expect you know Set interface, its methods and features etc.

Let us write a small example on Set Iterator Java and then explain.
import java.util.*;
public class PrintElements
 public static void main(String args[])
   Set s1 = new HashSet();
   s1.add(new Date());

   Iterator it = s1.iterator();

   System.out.println("\nSet Elements:\n");

Set Iterator Java
Output Screenshot on Set Iterator Java

A Set object sl is created and added elements with add() method. iterator() method of Set returns an object of Iterator interface containing all the elements of Set. 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.