Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javatutorial Iterator in Java Example

Related Tutorials


 
 

Share on Google+Share on Google+

Iterator in Java Example

Advertisement
We are going to discuss about iterator in java. Iterator is an interface in the collection framework and it works similar to the Enumeration. The java iterator traverse through all the elements of the collection. We have used three method hasNext() and next(). and remove() method. However we can also use while loop and for loop.

Iterator in Java Example

We are going to discuss about iterator in java. Iterator is an interface in the collection framework and it works similar to the Enumeration. The java iterator traverse through all the elements of the collection. We have used three method hasNext() and next(). and remove() method. However we can also use while loop and for loop.

  • hasNext() Method:-The hasNext() method returns true if the iteration has many elements.
  • next() method:- The next () method returns the next element in the iteration.
  • remove() method:- The remove method removes the last element returned by the iterator from the underlying collection. We can call this method only once.

In this example, we have used hasNext() and next() method.

Example

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

public class SimpleTest {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add("Apple");
		list.add("Banana");
		list.add("Orange");
		list.add("Apricot");
		list.add("Carrot");

		useWhileLoop(list);

		useForLoop(list);
	}
   
	private static void useWhileLoop(Collection aFlavours) {
		Iterator Iter = aFlavours.iterator();
		while (Iter.hasNext()) {
			System.out.println(Iter.next());
		}
	}

     // Note that this for-loop does not use an integer index.
	private static void useForLoop(Collection aFlavours) {
		for (Iterator Iter = aFlavours.iterator(); Iter.hasNext();) {
			System.out.println(Iter.next());
		}
	}
}

OutPut:

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  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.

Posted on: July 12, 2013

Related Tutorials

Discuss: Iterator in Java Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com