Monday, January 28, 2008

How to use List interface

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:




Adds an objects to the collection


Removes all objects from the collection.


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


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


Returns true if the collection has no elements.


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


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


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

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

//backword direction
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

No comments: