Sobes.tech
Junior — Middle

When adding an element to the end of a collection, which data structure — ArrayList or LinkedList — is faster?

sobes.tech AI

Answer from AI

When adding an element to the end of a collection:

  • ArrayList usually performs faster if there is enough space in the array because adding occurs in amortized O(1) time — the element is simply written into the next free cell.

  • If the array is full, it is resized (copied into a new array), which takes more time.

  • LinkedList always adds an element to the end in O(1) time, as a new node is simply created and links are updated.

In practice, for adding to the end, if array resizing is not considered, ArrayList is faster due to better data locality and lower overhead for node management. LinkedList is advantageous if frequent insertions/deletions in the middle of the list are needed.

Example:

ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(10); // Fast if there is enough space

LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(10); // Always fast, but with more overhead
When adding an element to the end of a collection… - sobes.tech