I understood that LinkedList
is implemented as a double linked list. Its performance on add and remove is better than Arraylist
, but worse on get and set methods.
Does that mean I should choose LinkedList
over Arraylist
for inserting?
I wrote a small test and found ArrayList
is faster in inserting. Then how does linked list faster than ArrayList
?
Please refer the below example which I have done.
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class TestLinkedList {
public static void main(String[] args) {
long lStartTime = new Date().getTime();
System.out.println("lStartTime:: " + lStartTime);
List<Integer> integerList = new LinkedList<Integer>();
for (int i = 0; i < 10000000; i++) {
integerList.add(i);
}
long lEndTime = new Date().getTime();
System.out.println("lEndTime:: " + lEndTime);
long difference = lEndTime - lStartTime;
System.out.println("Elapsed milliseconds: " + difference);
}
}