I was working with LinkedList and ArrayList and I know the concept of adding the elements into the ArrayList and LinkedList, but I when run code of checking the time of insertion then I got different insertion time again and again, for both LinkedList and ArrayList.
Sometimes the insertion time of LinkedList comes better and vice versa, how is it happening exactly, can any one please tell me.
import java.util.ArrayList;
public class Time
{
public static void main(String args[])
{
int n=100000;
long milis = System.currentTimeMillis();
ArrayList obj=new ArrayList();
for(int k=0;k<=n;k++)
{
obj.add(k);
}
System.out.println("insert arraylist takes "
+(System.currentTimeMillis()-milis)+" ms");
}
}
Output of this program is
1)insert arraylist takes 13 ms 2)insert arraylist takes 9 ms
The second code is
import java.util.LinkedList;
public class Time1
{
public static void main(String args[])
{
int n=100000;
long milis = System.currentTimeMillis();
LinkedList obj=new LinkedList();
for(int k=0;k<=n;k++)
{
obj.add(k);
}
System.out.println("insert linklist takes "
+(System.currentTimeMillis()-milis)+" ms");
}
}
The output of this
1)insert linklist takes 8 ms
2)insert linklist takes 17 ms