ArrayList vs LinkedList in Java with Examples

8/16/2025

#ArrayList vs LinkedList in Java with Examples

Go Back

ArrayList vs LinkedList in Java with Examples

Both ArrayList and LinkedList are popular implementations of the List interface in Java. They provide different ways of storing and managing data, making them suitable for different scenarios. Let’s explore their differences with examples.


#ArrayList vs LinkedList in Java with Examples

ArrayList in Java

  • Definition: Uses a dynamic array to store elements.

  • Best For: Fast random access and iteration.

  • Performance:

    • Access: O(1)

    • Insertion (end): O(1) amortized

    • Insertion/Deletion (middle): O(n)

Example:

import java.util.*;

public class ArrayListExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        System.out.println("ArrayList: " + fruits);
    }
}

LinkedList in Java

  • Definition: Uses a doubly linked list to store elements.

  • Best For: Frequent insertions and deletions.

  • Performance:

    • Access: O(n)

    • Insertion/Deletion (start or middle): O(1)

    • Iteration: O(n)

Example:

import java.util.*;

public class LinkedListExample {
    public static void main(String[] args) {
        List<String> animals = new LinkedList<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("LinkedList: " + animals);
    }
}

Key Differences Between ArrayList and LinkedList

FeatureArrayListLinkedList
Data StructureDynamic ArrayDoubly Linked List
Access SpeedFast (O(1))Slower (O(n))
Insertion/DeletionSlow in middle (O(n))Fast at beginning/middle (O(1))
Memory UsageLess memory overheadMore memory (due to node pointers)

When to Use What?

  • Use ArrayList when you need fast access and iteration.

  • Use LinkedList when you need frequent insertions/deletions.

  • Avoid LinkedList when memory is a concern.


Final Thoughts

Both ArrayList and LinkedList implement the List interface, but their internal workings make them suitable for different use cases. By understanding their differences, you can make better decisions about which collection to use in your Java applications.

Table of content