In this method, you can find the next single element from the iteration at a time.
next( ) method of Iterator Interface in java.
In the following example we will show you how can next( ) method be implemented in Iterator interface.
Syntax
public Object next( )
This method returns the succeeding element (Object) of a collection in the iteration.
In this method, you can retrieve the next single element from the iteration at a time. It gives the just next element in a list from the current position of that element which is traversed just before. This method is used with the Iterator object. It is useful for finding out the element from collection sequentially, if collection has further more elements. If a collection has further not more elements, 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 Iterator interface. This example will help you to understand how can you find the element from a collection. Through this example we will show you how iterator( ) method be used and how the next( ) method be used for finding the next element from collection using Iterator object.
Example:-
package Devmanuals.com; import java.util.List; import java.util.ArrayList; import java.util.Iterator; public class IteratorNext { public static void main(String[] args) { ArrayList alist = new ArrayList(); alist.add("A"); alist.add("B"); alist.add("C"); alist.add("D"); alist.add("E"); System.out.println("Elements of list = "+alist); System.out.println("Size of list = "+alist.size()); Iterator itr = alist.iterator(); System.out.println("List has elements : "+itr.next()); System.out.println("List has elements : "+itr.next()); System.out.println("List has elements : "+itr.next()); System.out.println("List has elements : "+itr.next()); System.out.println("List has elements : "+itr.next()); //For next line the next( ) method will throws exception System.out.println("List has elements : "+itr.next()); } }
Output :
Elements of list = [A, B, C, D, E] Size of list = 5 List has elements : A List has elements : B List has elements : C List has elements : D List has elements : E Exception in thread "main" java.util.NoSuchElementExceptionat java.util.AbstractList$Itr.next(Unknown Source) at Devmanuals.com.IteratorNext.main( IteratorNext.java:24) |
[ 0 ] Comments