What is Iterator

What is Iterator

Answer : With release of java JDK 1.2 java.util.Iterator interface been introduced. It allows to iterator over a collection of objects. It provides three methods:

  • hasNext() – returns true if the iteration got more elements
  • next() – returns next element in iteration
  • remove() – removes from collection

Please see example below:

package com.javahonk.iteratortest;

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorTest {

    public static void main(String[] args) {

	ArrayList<String> arrayList = new ArrayList<String>();

	arrayList.add("A");
	arrayList.add("A");
	arrayList.add("C");
	arrayList.add("B");
	arrayList.add("D");
	arrayList.add("F");

	// Iterator display content
	System.out.print("Contents of arrayList: ");

	Iterator<String> itr = arrayList.iterator();
	while (itr.hasNext()) {
	    String element = itr.next();
	    System.out.print(element + " ");
	}
    }

}

 

Output:

What is Iterator

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *