Home Tutorial Java Iterator Java Collection iterator with example

 
 

Java Collection iterator with example
Posted on: November 3, 2009 at 12:00 AM
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

Related Tags for Java Collection iterator with example:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.