List Iterator Java


In Java, Data structures, known as collection classes or collections framework, is a big topic as it involves many many classes. Choosing a right data structure, in Java, requires good experience and once chosen, writing part, a novice can do. DS is simple in Java because of no pointers. In this tutorial list iterator is discussed.

What you have done in C/C++ for a linked list and how much time you spent, forget in Java because linked list in Java is a class and methods exist to manipulate the elements. More operations on linked list can be done (perhaps, you have not done in C/C++, like deleting a range of nodes) in no time with predefined methods.

For retrieval many styles exist like using Enumeration, Iterator, ListIterator, traditional for loop and enhanced for loop (of JDK 1.5 fame).

Following example uses list iterator to iterate and print the elements of ArrayList.
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Date;
public class LIExample
{
  public static void main(String args[])
  {
    ArrayList al1 = new ArrayList();
    al1.add("Hyderabad");
    al1.add(100);
    al1.add(10.6);
    al1.add(new Date());

    ListIterator li = al1.listIterator();

    System.out.println("\nArrayList elments are:");
    while(li.hasNext())
    {
      System.out.print(li.next() + " ");
    }
  }
}

List Iterator JavaOutput Screenshot on List Iterator Java

ArrayList al1 = new ArrayList();
al1.add(“Hyderabad”);

An ArrayList object al1 is created and added with different elements with add() method. As it is not generics DS, the compiler raises a warning. Observe the Screenshot.

ListIterator li = al1.listIterator();

The listIterator() method of ArraYlist returns an object of ListIterator interface containing all the elements of al1.

while(li.hasNext())
{
System.out.print(li.next() + ” “);
}

With hasNext() method, all the elements of the ListIterator object li are iterated one-by-one. Each element iterated is returned with next() method.

For more on ListItrator see ListIterator.

To know all iterators see All Iterators in a Nutshell

Leave a Comment

Your email address will not be published. Required fields are marked *