Sobes.tech
Junior

What are the main differences between List and LinkedList in Java?

sobes.tech AI

Answer from AI

List - an interface representing an ordered collection of elements. LinkedList is one of the implementations of the List interface.

Main differences:

  1. Internal structure:

    • ArrayList uses a dynamic array.
    • LinkedList uses a doubly linked list.
  2. Performance of operations:

    • Adding/removing in the middle: LinkedList is faster as it only requires changing links (O(1) after locating the position). ArrayList requires shifting elements (O(n)).
    • Adding/removing at the end: ArrayList is faster (O(1) on average). LinkedList also O(1).
    • Adding/removing at the beginning: LinkedList is faster (O(1)). ArrayList requires shifting elements (O(n)).
    • Access by index (get): ArrayList is faster as it is based on an array (O(1)). LinkedList requires traversal (O(n)).
    • Iteration: Both collections have similar performance when traversing elements with an iterator.
  3. Memory usage:

    • LinkedList requires more memory per element as it needs to store references to the previous and next elements, in addition to the value itself. ArrayList stores only values.
  4. Implemented interfaces:

    • Both implement List. LinkedList additionally implements Deque and Queue.

Summary table:

Operation ArrayList LinkedList
Access by index O(1) O(n)
Add at the end O(1) O(1)
Add at the beginning O(n) O(1)
Add in the middle O(n) O(1)
Remove from end O(1) O(1)
Remove from beginning O(n) O(1)
Remove from middle O(n) O(1)
Iteration O(n) O(n)

Choosing between ArrayList and LinkedList depends on the predominant operations to be performed on the collection. If frequent index access or frequent add/remove operations at the end are required, ArrayList is preferable. If frequent add/remove operations at the beginning or middle are needed, LinkedList will be more efficient.