next( ) method of ListIterator Interface in java.

next( ) method of ListIterator Interface in java.


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

In this method, you can find the next element from the iteration, one element at a time in forward direction.

next( ) method of ListIterator Interface in java.

In the following example we will show you how can next( ) method is implemented in ListIterator interface.

Syntax

public Object next( )

This method gives the succeeding element (Object) in the iteration when traversing in forward direction of a collection.

In this method, you can find the next element from the iteration, one element at a time in forward direction. It gives the just next element in a list from the current position of that element which is traversed. This method is used with ListIterator object. It gives the next value till then a collection has elements. If a collection contains no element, it displays 'NoSuchElementException' exception.

Parameter description

This method takes no argument.

Example of next( ) method

In this example we will show you how does next( ) method work in a collection using ListIterator interface. This example will help you to understand how can you find the element in forward direction into a collection. Through this example we will show you how next( ) method uses ListIterator object and how does it display a new value from list. 

Example:- 

package Devmanuals.com;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
public class ListIteratorNext {
  public static void main(String[] args) {
    LinkedList llist = new LinkedList();
    llist.add("1");
    llist.add("2");
    llist.add("3");
    llist.add("4");
    llist.add("5");
    System.out.println("Elements of list = " + llist);
    System.out.println("Size of list = " + llist.size());
    ListIterator litr = llist.listIterator();
    System.out.println("List has elements : " + litr.next());
    System.out.println("List has elements : " + litr.next());
    System.out.println("List has elements : " + litr.next());
    System.out.println("List has elements : " + litr.next());
    System.out.println("List has elements : " + litr.next());
    // For next line the next( ) method will throws exception
    System.out.println("List has elements : " + litr.next());
  }
}

Output : 

Elements of list = [12345]
Size of list = 5
List has elements : 1
List has elements : 2
List has elements : 3
List has elements : 4
List has elements : 5
Exception in thread "main" java.util.NoSuchElementException
  at java.util.LinkedList$ListItr.next(Unknown Source)
  at Devmanuals.com.ListIteratorNext.main(ListIteratorNext.java:24)

Download Source code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics