Advertisement



< 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.



Advertisement




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();

arr.add("F");
arr.add("O");
arr.add("R");
arr.add("W");
arr.add("A");
arr.add("R");
arr.add("D");
ListIterator itr = arr.listIterator();

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


System.out.println();

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

while(itr.hasPrevious())
{
System.out.print(itr.previous() + " " );
}

System.out.println();
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 -




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



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement