ListIterator | Java

/ListIterator | Java

Like Iterator, ListIterator is a Java Iterator, which is used to iterate elements one-by-one from a List implemented object. Important details about ListIterator

  • It extends Iterator interface.
  • It is useful only for List implemented classes.
  • Unlike Iterator, It supports all four operations: CRUD (CREATE, READ, UPDATE and DELETE).
  • Unlike Iterator, It supports both Forward Direction and Backward Direction iterations.
  • It is a Bi-directional Iterator.
  • We can use list Iterator for all List implemented classes like ArrayList, CopyOnWriteArrayList, LinkedList, Stack, Vector etc.

 

ListIterator Methods

Java ListIterator interface has the following Methods.

  • void add(E e): Inserts the specified element into the list.
  • boolean hasNext(): Returns true if this list iterator has more elements when traversing the list in the forward direction.
  • boolean hasPrevious(): Returns true if this list iterator has more elements when traversing the list in the reverse direction.
  • E next(): Returns the next element in the list and advances the cursor position.
  • int nextIndex(): Returns the index of the element that would be returned by a subsequent call to next().
  • E previous(): Returns the previous element in the list and moves the cursor position backwards.
  • int previousIndex(): Returns the index of the element that would be returned by a subsequent call to previous().
  • void remove(): Removes from the list the last element that was returned by next() or previous().
  • void set(E e): Replaces the last element returned by next() or previous() with the specified element.

 

Example

public class ListIteratorDemo 
{
  public static void main(String[] args) 
  {
    List<String&gt names = new LinkedListt<>();
    names.add("Rams");
    names.add("Posa");
    names.add("Chinni");
    
    // Getting ListIterator
    ListIterator<String&gt listIterator = names.listIterator();
    
    // Traversing elements in forward direction
    while(listIterator.hasNext()){
      System.out.println(listIterator.next());			
    }	
    
    // Traversing elements in backward direction
    while(listIterator.hasPrevious()){
      System.out.println(listIterator.previous());			
    }
  }
}

 

August 14th, 2019|Categories: Programming|Tags: |
avatar
  Subscribe  
Notify of