In this method, you can find the previous element by iteration, one element at a time from the list. This method is repeatable it may be called repeatedly to iterate
previous( ) method of ListIterator Interface in java.
In the following example we will show you how can previous( ) method is implemented in ListIterator interface.
Syntax
public Object previous( )
This method gives previous element (Object) in the list.
In this method, you can find the previous element by iteration, one element at a time from the list. This method is repeatable it may be called repeatedly to iterate through the list in backward direction. The previous( ) method can be combined with next( ) to go backward and forward. This method is used with ListIterator object. It gives the previous value till a collection has more elements. If a collection does not contain more elements, it displays 'NoSuchElementException' exception.
Parameter description
This method takes no argument.
Example of previous( ) method
In this example we will show you how does previous( ) method work in a collection using ListIterator interface. This example will help you to understand how can you find the element in backward direction into a collection. Through this example we will show you how previous( ) method uses ListIterator object and how it displays a new value from list sequentially, one element at a time.
Example:-
package Devmanuals.com; import java.util.List; import java.util.LinkedList; import java.util.ListIterator; public class ListIteratorPrevious { public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.add("A"); llist.add("B"); llist.add("C"); llist.add("D"); llist.add("E"); System.out.println("Elements of list = " + llist); System.out.println("Size of list = " + llist.size()); ListIterator litr = llist.listIterator(); while(litr.hasNext()) litr.next(); System.out.println("Elements in reverse order : "); System.out.println(litr.previous()); System.out.println(litr.previous()); System.out.println(litr.previous()); System.out.println(litr.previous()); System.out.println(litr.previous()); // For next line the previous( ) method will throws exception System.out.println("\t-------------THROWS EXCEPTION------------- "); System.out.println(litr.previous()); } }
Output :
Elements of list = [A, B, C, D, E] Size of list = 5 Elements in reverse order : E D C B A -------------THROWS EXCEPTION------------- Exception in thread "main" java.util.NoSuchElementExceptionat java.util.LinkedList$ListItr.previous(Unknown Source) at Devmanuals.com.ListIteratorPrevious.main( ListIteratorPrevious.java:29) |
[ 0 ] Comments