Home Tutorial Java Iterator Iterate java collection

 
 

Iterate java collection
Posted on: November 2, 2009 at 12:00 AM
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

Related Tags for Iterate java collection:


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.