Java Collection iterator with example


 

Java Collection iterator with example

In this Java tutorial we will see how to use the iterator interface with Collection. We will create an example to display the contents of the Collection.

In this Java tutorial we will see how to use the iterator interface with Collection. We will create an example to display the contents of the Collection.

  • The Java Collection Iterator is present at the highest level interface in the Collection framework.
  • Iterator interface has methods for traversing, but Collection doesn't has iterator() method.
  • So create object with reference to other collection class.Those class should have iterator() method.


Example of Java Collection Iterator


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

public class collection2 {

	public static void main(String[] args) {
		Collection c = new ArrayList();
		c.add("rose");
		c.add("Lotus");
		c.add("Marigold");
		c.add("Jasmine");
		Iterator ir = c.iterator();

		while (ir.hasNext()) {
			System.out.println(ir.next());
		}
	}
}

Output

rose Lotus Marigold Jasmine

Ads