Video in progress

When would you pick ArrayList over LinkedList, and the other way around?

Almost always ArrayList: indexed access is O(1), the data sits densely in memory, and it is friendly to the CPU cache. LinkedList only makes sense when you constantly add and remove at the head of the list, and even then ArrayDeque is usually better.

📖 Answer

ArrayList is just an array inside. get(i) takes one step, and add at the end is usually O(1) too. Only when the array is full does it get copied into a bigger one.

LinkedList is a chain of separate nodes (Node), each pointing to the previous and the next one. For get(500_000) you have to walk through half of the list.

List<String> names = new ArrayList<>();   // the default choice
Deque<String> tasks = new ArrayDeque<>(); // when you need a queue or a stack

Textbooks say "inserting in the middle of a LinkedList is O(1)". But first you have to find that spot, and that is O(n). In practice the System.arraycopy shift in ArrayList often turns out faster, because the memory is contiguous.

One more thing: LinkedList allocates an extra object for every element, which adds up to real memory at a million elements.