java left logo
java middle logo
java right logo
 

Home arrow Java SE Tips arrow java.util arrow How to use List interface
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 4100
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
How to use List interface E-mail
User Rating: / 117
PoorBest 

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 an  objects 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

 Related Tips

 
< Prev   Next >
 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.