Problem : Create a program that implement Iterator class.
Program :Step 1 - CodingCreate a text file c:\sunilos\TestIterator.java and copy below contents.import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /* * A program to read all elements sequentially from a * List with help of Iterator interface */ public class TestIterator { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("Basanti-> Kahan jana hai "); list.add("Jay-> Ramgdh jana hai "); list.add("Basanti-> yuki Basanti ko jada bate karne ki aadat to hai nehai.."); list.add("Basanti-> isaliye 2 rupay lagaga "); list.add("Viru-> Tuhara nam kya hai basanti " ); // Get an iterator from List Iterator it = list.iterator(); System.out.println("From Iterator "); //Check if Iterator has next element while (it.hasNext()) { //Get next element System.out.println(it.next()); } } } Step 2 - Deployment
Step 3 - Testing
OutputFrom Iterator Basanti-> Kahan jana hai Jay-> Ramgdh jana hai Basanti-> yuki Basanti ko jada bate karne ki aadat to hai nehai.. Basanti-> isaliye 2 rupay lagaga Viru-> Tuhara nam kya hai basanti FAQWhat is Iterator?An object that implements the Iterator interface generates a series of elements, one at a time. Successive calls to thenext() method return element in the Iterator.
Iterator it = list.iterator(); //Check if Iterator has next element while (it.hasNext()) { //Get next element System.out.println(it.next()); } Iterator takes the place of Enumeration in the Java collections framework. What are important methods in Iterator?
What are differences between Enumeration and Iterator?An
iterator over a collection. Iterator takes the place of Enumeration in
the Java collections framework. Iterators differ from enumerations in two ways: i. Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. ii. Method names have been improved. In other words Iterator can remove an element whereas Enumeration can not. Most Interesting methods?
|