Difference Between ArrayList and LinkedList in Java

java dev.to

ArrayList and LinkedList are two commonly used classes in the Java Collections Framework. Both implement the List interface and allow duplicate elements while maintaining insertion order. However, they differ in how data is stored and how operations are performed.


ArrayList

ArrayList uses a dynamic array to store elements. It provides fast access to elements using indexes and is suitable when data retrieval is performed frequently.

Features of ArrayList

  • Uses a dynamic array internally.
  • Maintains insertion order.
  • Allows duplicate elements.
  • Fast random access using indexes.
  • Slower insertion and deletion in the middle of the list because elements need to be shifted.

LinkedList

LinkedList uses a doubly linked list to store elements. Each element is stored as a node containing data and references to the previous and next nodes.

Features of LinkedList

  • Uses a doubly linked list internally.
  • Maintains insertion order.
  • Allows duplicate elements.
  • Fast insertion and deletion operations.
  • Slower access to elements because it must traverse the list.

ArrayList vs LinkedList

Feature ArrayList LinkedList
Definition A dynamic array implementation of the List interface. A doubly linked list implementation of the List interface.
Data Storage Stores elements in a dynamic array. Stores elements as connected nodes.
Access Time Fast access using index (O(1)). Slower access because it traverses nodes (O(n)).
Insertion/Deletion Slower in the beginning or middle because elements need to be shifted. Faster because nodes can be added or removed without shifting elements.
Memory Usage Uses less memory. Uses more memory due to previous and next references.
Iteration Generally faster for traversing elements. Slightly slower than ArrayList.
Best Use Case Frequent searching and accessing of elements. Frequent insertion and deletion of elements.

When to Use ArrayList?

Use ArrayList when:

  • You frequently access elements using indexes.
  • Read operations are more common than insertions and deletions.
  • Better performance for searching and retrieving data is required.

Example:

ArrayList list = new ArrayList();
list.add("Java");
System.out.println(list.get(0));
Enter fullscreen mode Exit fullscreen mode

When to Use LinkedList?

Use LinkedList when:

  • You frequently insert or remove elements.
  • Queue or Deque operations are required.
  • The application performs more updates than searches.

Example:

LinkedList list = new LinkedList();
list.addFirst("Java");
list.removeLast();
Enter fullscreen mode Exit fullscreen mode

Source: dev.to

arrow_back Back to Tutorials