iterator( )method of List Interface in Java.

iterator( )method of List Interface in Java.


Posted in : Core Java Posted on : January 7, 2011 at 6:57 PM Comments : [ 0 ]

In the following example we will show you how can you traverse the elements in existing list using iterator( ) method of List interface in java.

iterator( )method of List Interface in Java.

In the following example we will show you how can you traverse the elements in existing list using iterator( ) method of List interface in java.

Syntax

Iterator iterator( )

This method returns an Iterator across the elements in the underlying list in proper sequence.

In this method, you can traverse every element in the collection, but one by one. To use an iterator in any of the collection, follow these steps:

* Find an iterator to the start of the collection by calling the collection's iterator( ) method.

* Set a loop that makes a call to hasNext( ). It returns true if list contains more element.

*  You can find element from list by calling  next( ) method.
Parameter description

This method does not take any argument.

Example of iterator( ) method

In this example we will show you how does iterator ( ) method works in List interface. This example will help you to understand how can you iterate in list. Through this example we will show you the iteration and display the element of list .

Example:- 

package Devmanuals.com;
import java.util.List;
import java.util.ArrayList;
public class ListIterator {
public static void main(String[] args) {
ArrayList al = new ArrayList();
for(int i=0; i<=10;i++)
al.add(i);
System.out.println("Display number from 0 to 10 : ");
Iterator b = al.iterator();
System.out.println("Is list contain more elements ? "+b.hasNext());
while(b.hasNext())
{
if(b.hasNext()= = true)
System.out.println( b.next() );
else
System.out.println("List has no more elements");
}
}
}

Output :

Display number from 0 to 10 :
Is list contain more elements ? true
0
1
2
3
4
5
6
7
8
9
10

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics