Share on Google+Share on Google+

Java Collection iterator with example

Ads
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

Advertisements

Posted on: November 3, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.