Home Tutorial Java Iterator Iterate java collection

 
 

Share on Google+Share on Google+
Iterate java collection
Posted on: November 2, 2009 at 12:00 AM
Advertisement
In this tutorial we will learn about the Iterator interface and its use with the collection interface.We will create an example to print the content of the collection using the iterator() method.

  • Collection is the top level interface of the Collection framework.
  • Iterator interface has methods for traversing over the elements of the collection.
  • But Collection doesn't has iterator() method.
  • So create object with the reference of other collection which supports iterator() method


Example
import java.util.*;

public class collection {

	public static void main(String[] args) {
		Collection c = new ArrayList();

		String names[] = { "jack", "rock", "mac", "joe" };
		for (int i = 0; i < names.length; i++) {
			c.add(names[i]);
		}
		Iterator it = c.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output

jack rock mac joe
Advertisement

Related Tags for Iterate java collection:


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 2, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com