Share on Google+Share on Google+

Iterator Java Loop

Advertisement
In this part of the tutorial we will learn to use all the loops .We will create an example to display the content of the arraylist.

  • With iterator all three loops can be used.
  • While, dowhile, and for loop is easy to use with iterator.


Example Java Loop Iterator

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class loop {
	public static void main(String[] args) {
		List l = new ArrayList();
		for (int i = 1; i < 6; i++) {
			l.add(i);
		}
		Iterator it = l.iterator();
		System.out.println("while loop");
		while (it.hasNext()) {
			System.out.print(it.next() + "\t");
		}
		Iterator it1 = l.iterator();
		System.out.println("\ndo .. while");
		do {
			System.out.print(it1.next() + "\t");
		} while (it1.hasNext());
		Iterator it2 = l.iterator();
		System.out.println("\nfor loop");
		for (; it2.hasNext();) {
			System.out.print(it2.next() + "\t");
		}
	}
}

Output :

while loop 1 2 3 4 5 do .. while 1 2 3 4 5 for loop 1 2 3 4 5

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.