In this section we will discuss how can you iterate in list using listIterator ( ) method in List interface in java.
listIterator ( ) method of List Interface in Java
In this section we will discuss how can you iterate in list using listIterator ( ) method in List interface in java.
Syntax
public ListIterator listIterator( )
This method returns a list-iterator of the elements in proper sequence.
This method works like an Iterator iterator ( ) method. This method allows you to traverse the list in either direction - forward or backward direction. We can modify the list while iterating i.e. we are allowed to replace existing element with the new element and to add new elements in list. In a list of length n there are n+1 valid index values from 0 to n inclusive.
To use a listIterator( ) in any of the collection, we should follow these steps:
* Find an iterator to the start of the collection by calling the collection's
listIterator( ) method.
* Set a loop that makes a next call, hasNext( ). It returns true if list contains more element.
* Further set a loop that makes a previous call, hasPrevious( ). It returns true if list contains more element.
* You can find element in forward direction from list by calling next( ) method.
* Further you can find element in backward direction from list by calling previous( ) method.
Parameter description
This method does not take any argument but, returns list iterator of the elements in proper sequence of an existing list.
Example of listIterator( ) method
In this example we will show you how does listIterator ( ) method works in List interface. This example will help you to understand how can you iterate in list in forward and backward direction. Through this example we will show you the iteration method, display of elements after iteration, and replacing the element of a list.
Example:-
package Devmanuals.com; import java.util.*; import java.util.ListIterator; public class LISTListIterator { public static void main(String args[]){ LinkedListll = new LinkedList (); ll.add("Ram"); ll.add("Shyam"); ll.add("Ghanshyam"); ll.add("Sohan"); ll.add("Mohan"); ListIterator li = ll.listIterator(); System.out.println("Is list contains element : "+li.hasNext()); System.out.println("//Element in forward order : "); while (li.hasNext()){ System.out.println(li.next()); } System.out.println("Is list has previous element : "+li.hasPrevious()); System.out.println("//Element in reverse order : "); while (li.hasPrevious()){ System.out.println(li.previous()); } while (li.hasNext()){ String s=(String)li.next(); if(s.equals("Sohan")) li.set("Rohan"); } System.out.println("After replacing name new list is : "+ll); } }
Output :-
Is list contains element : true //Element in forward order : Ram Shyam Ghanshyam Sohan Mohan Is list has previous element : true //Element in reverse order : Mohan Sohan Ghanshyam Shyam Ram After replacing name in old list then new list is : [Ram, Shyam,
Ghanshyam, Rohan, Mohan] |
[ 0 ] Comments