Saturday, August 22, 2009

Efficient use of add(0,object) method of java.util.List

If you want an efficient access of add(0,object) method of List interface, where quick and random access of the list is not a primary concern. You must use java.util.LinkedList instead of ArrayList,LinearList and Queue.

You can check the efficiency of LinkedList inplementation by the given example:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class EfficientList
{

/**
* @author Prabir Karmakar
*/
public static void main(String[] args)
{
List list = new ArrayList();
System.out.println("Using ArrayList..");
System.out.println("Before Manupulation:"
+System.currentTimeMillis());
for(int i=0;i<10000;i++)
{
list.add(0, "prabir"+i);
}
System.out.println("After Manupulation:"
+System.currentTimeMillis());

List list1 = new LinkedList();
System.out.println("Using LinkedList..");
System.out.println("Before Manupulation:"
+System.currentTimeMillis());
for(int i=0;i<10000;i++)
{
list1.add(0, "raj"+i);
}
System.out.println("After Manupulation:"
+System.currentTimeMillis());
}
}

Program Output

Using ArrayList..
Before Manupulation:1250946828955 (current time Millis)
After Manupulation:1250946829024 (current time Millis)
Using LinkedList..
Before Manupulation:1250946829024 (current time Millis)
After Manupulation:1250946829034 (current time Millis)

No comments:

Post a Comment