Answer:
Check the explanation
Explanation:
CODE TO COPY:
File: ArrayListVsLinkedlIst.java
// ArrayListVsLinkedlIst class implementation
import java.util.*;
public class ArrayListVsLinkedlIst
{
public static void main(String[] args)
{
// create a constant for the size of each list
final int SIZE = 300000;
// create the required objects
List<Integer> aList = new ArrayList<Integer>();
List<Integer> lList = new LinkedList<Integer>();
// declare the required variables
long start, end;
int i;
// comparison between the efficiency of the add() method
// from the ArrayList and LinkedList classes
System.out.println("Time in milliseconds to add " + SIZE
+ " numbers to each list ...");
start = System.currentTimeMillis();
for (i = 0; i < SIZE; i++)
{
aList.add(i);
}
end = System.currentTimeMillis();
System.out.println("ArrayList: " + (end - start) + " ms");
start = System.currentTimeMillis();
for (i = 0; i < SIZE; i++)
{
lList.add(i);
}
end = System.currentTimeMillis();
System.out.println("LinkedList: " + (end - start) + " ms");
// comparison between the efficiency of the get() method
// from the ArrayList and LinkedList classes
System.out.println("\nTime in milliseconds to get " + SIZE
+ " numbers from each list ...");
start = System.currentTimeMillis();
for (i = 0; i < SIZE; i++)
{
aList.get(i);
}
end = System.currentTimeMillis();
System.out.println("ArrayList: " + (end - start) + " ms");
start = System.currentTimeMillis();
for (i = 0; i < SIZE; i++)
{
lList.get(i);
}
end = System.currentTimeMillis();
System.out.println("LinkedList: " + (end - start) + " ms");
// comparison between the efficiency of the remove() method
// from the ArrayList and LinkedList classes
System.out.println("\nTime in milliseconds to remove " + SIZE
+ " numbers from each list ...");
start = System.currentTimeMillis();
for (i = 0; i < SIZE; i++)
{
aList.remove(0);
}
end = System.currentTimeMillis();
System.out.println("ArrayList: " + (end - start) + " ms");
start = System.currentTimeMillis();
for (i = 0; i < SIZE; i++)
{
lList.remove(0);
}
end = System.currentTimeMillis();
System.out.println("LinkedList: " + (end - start) + " ms");
}
} // end of ArrayListVsLinkedlIst class
The screenshot and output images can be seen below.