List interface is an extension of Collection interface. List interface indicates the behavior of the collection of objects. It allows duplicate objects and one or more elements to be null.

Useful methods of the List Interface:

Method

Usage

add()

Adds anobjects to the collection

clear()

Removes all objects from the collection.

contains()

Returns true if a special object is an element with in the collection.

get()

Returns the element at the specified index position in this collection.

isEmpty()

Returns true if the collection has no elements.

listIterator()

Returns a ListItertor object for the collection which may then be used to retrieve an object.

Remove()

Removes the element at the specified index position in this collection.

size()

Returns the number of elements in the collection.

In this code ListIterator is used for reading the objects of the list. It allows reading objects from the collection in both the forward and backward directions.

 import java.util.*;

public class DemoList {

  public static void main(String[] args) {

    List ls = new LinkedList();

    for(int i=1; i<=5; i++){
      ls.add(new StringBuffer("Object " + i));
    }

    //display how many objects are in the collection
    System.out.println("The collection has " + ls.size() + "objects");

    //Instantiate a ListIterator
    ListIterator li = ls.listIterator();
    System.out.println("Forward Reading");

    //Forward direction
    while(li.hasNext()){
      System.out.println(" " + li.next());
    }

    System.out.println("Backward Reading");

    //backword direction
    while(li.hasPrevious()){
      System.out.println(" " + li.previous());
    }
  }

}

Output Screen:

The collection has 5objects
Forward Reading
 Object 1
 Object 2
 Object 3
 Object 4
 Object 5
Backward Reading
 Object 5
 Object 4
 Object 3
 Object 2
 Object 1