ListIterator Interface in Java


Prev Tutorial Next Tutorial

ListIterator Interface in Java

It is one of the predefined interface present in java.util.* package. The ListIterator interface object is always used for retrieving the data from any collection framework either forward direction or backward direction or in both direction. Like Iterator interface object, ListIterator interface object is pointing just before the first element of any collection framework variable.

Methods of ListIterator Interface

  • public boolean hasNext(): Returns true if the ListIterator has more elements when traversing the list in the forward direction.
  • public object next(): Return the next elements in the list.
  • public boolean hasprevious(): Return true if the ListIterator has more elements when traversing in list in reverse direction.
  • public object previous(): Return the previous elements in the list.
  • public object previousIndex(): Return the index of the element that could be returned by subsequent call to previous method.
  • public object add(element): Insert the specified element into the list.
  • public object set(element): Replace the element returned by next or previous elements with the new element.
  • public object remove(): Remove from the list the last elements that was returned by next or previous methods.

Difference between Iterator and ListIterator

IteratorListIterator
1Iterator is one of the super Interface for ListIteratorListIterator is one of sub-Interface of Iterator
2This Interface is allow to retrieve the element only in forward directionThis Interface is allow to retrieve the element in both direction either in forward and backward direction.

Example of ListIterator

import java.util.*;

class ListIteratorDemo
{
public static void main(String args[])
{  

LinkedList<Integer> ll=new LinkedList<Integer>();  // creating arraylist
ll.add(10);
ll.add(20);
ll.add(30);

ListIterator li=al.listIterator();  // getting Iterator from arraylist to traverse elements  
System.out.println("Forward Direction");  
while(li.hasNext())
{  
System.out.println(li.next());  
  }  
System.out.println("Reverse Direction");  
while(li.hasPrevious())
{  
System.out.println(li.previous());  
  }  
 }  
}  

Output

Forward Direction
10
20
30
Reverse Direction
30
20
10

Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements