Home Tutorial Java Iterator Java Collection iterator with example

 
 

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

Related Tags for Java Collection iterator with example:


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.

Posted on: November 3, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com