So, I was watching a tutorial which explained why Linked list is faster that Array list in insertion and when the person inserted the elements in both of the lists, the Linked list was faster as expected. But when I copied the same code, the Array List inserted faster in all of the attempts when i ran this code:
long n = (long) 1E7;
long milliseconds = System.currentTimeMillis();
ArrayList al = new ArrayList();
for(int i = 0; i < n; i ++) {
al.add(i);
}
System.out.println("Insertion time for ArrayList takes: " + (System.currentTimeMillis() -
milliseconds) + " milliseconds");
LinkedList ll = new LinkedList();
milliseconds = System.currentTimeMillis();
for(int i = 0; i < n; i++) {
ll.add(i);
}
System.out.println("Insertion time for LinkedList takes: " + (System.currentTimeMillis() -
milliseconds) + " milliseconds");
In all of the attempts, the Array list was faster in inserting the elements.