< Prev
Next >

ListIterator in Collection classes

We already know that we can cycle over the elements of any collection class by calling iterator() method. For collection classes that implement List interface, we can iterate over their elements by not only iterator() method but also listIterator() method. listIterator() gives us an object that implements ListIterator interface.

Important features of ListIterator

Methods in ListIterator interface

Methods Description
void add(E obj) Inserts an object in the front of the list.
boolean hasNext() Returns true if there is a next element in a list, otherwise, returns false.
E next() Returns the next element in a list.
boolean hasPrevious() Returns true if there is a previous element in a list, otherwise, returns false.
E previous() Returns the previous element in a list.
void remove() Removes the current element from the list.
void set(E obj) Sets the value of the current element to value of obj.

Using ListIterator to iterate over a collection

In this code, we are cycyling over the elements of a generic ArrayList<String>, in both directions (forward and backward) by -

import java.util.*;

class ListIteratorDemo
public static void main(String... ar)
ArrayList arr= new ArrayList();

ListIterator itr = arr.listIterator();

System.out.println("Iteraring the list in forward direction");
System.out.print("Contents of ArrayList are : ");
System.out.print(itr.next() + " " );


System.out.println("Iteraring the list in backward direction");
System.out.print("Contents of ArrayList are : ");

System.out.print(itr.previous() + " " );

System.out.println("Size of arraylist = "+ arr.size());


Output is :

Iteraring the list in forward direction
Contents of ArrayList are : F O R W A R D
Iteraring the list in backward direction
Contents of ArrayList are : D R A W R O F
Size of arraylist = 6

Program Analysis

Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter

< Prev
Next >
< iterator() to iterate
Iterator v/s ListIterator >

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page