Skip to content

ArrayList vs LinkedList πŸš€ΒΆ

Prerequisites: Java Collections Overview

Mentor's Note: Both tools do the same thing (store a list of items), but they do it very differently under the hood. Choosing the wrong one can slow down your app significantly! πŸ’‘


🌟 The Scenarios: The Resizable Bench πŸ›‹οΈ & The Train πŸš‚ΒΆ

  • ArrayList (The Resizable Bench): Imagine a wooden bench. If more people come, you have to build a completely new, larger bench and move everyone to it. πŸ“¦
  • LinkedList (The Train): Every person is in their own carriage. To add someone, you just hook a new carriage to the back. πŸ“¦
  • The Result: ArrayList is fast for Sitting (Reading), but LinkedList is fast for Hooking (Inserting). βœ…

πŸ“– Key DifferencesΒΆ

1. Java ArrayListΒΆ

  • Logic: Uses a dynamic array.
  • Performance:
    • Get: \(O(1)\) (Instant access by index). ⚑
    • Add/Remove: \(O(n)\) (Slow, must shift other items).

2. Java LinkedListΒΆ

  • Logic: Each item (Node) points to the next and previous item.
  • Performance:
    • Get: \(O(n)\) (Slow, must walk through the carriages). ⏳
    • Add/Remove: \(O(1)\) (Fast, just change the hooks).

🎨 Visual Logic: The Memory Structure¢

graph LR
    subgraph ArrayList: ["Contiguous Memory 🧱"]
    A[0] --- B[1] --- C[2]
    end

    subgraph LinkedList: ["Linked Nodes πŸš‚"]
    D[Head] --> E[Item 1]
    E --> F[Item 2]
    F --> G[Tail]
    end

πŸ’» Implementation: The List LabΒΆ

import java.util.ArrayList;

// πŸ›’ Scenario: Storing a fixed set of results
ArrayList<String> students = new ArrayList<>();
students.add("Vishnu");
students.add("Ankit");

// ⚑ Fast retrieval
System.out.println(students.get(0)); 
import java.util.LinkedList;

// πŸ›’ Scenario: A Task Queue (Frequent changes)
LinkedList<String> tasks = new LinkedList<>();
tasks.addFirst("Priority 1");
tasks.addLast("Normal");

// πŸš€ Fast insertion at both ends
tasks.removeFirst();

πŸ“Š Sample Dry Run (ArrayList Growth)ΒΆ

Initial capacity: 10

Items Added Logic Internal Action
1-10 Fill existing array No move.
11 Array Full! πŸ›‘ Create new array (size 15)
11 Copy old to new All 10 items moved πŸš›

πŸ’‘ Interview Tip πŸ‘”ΒΆ

"Interviewers love asking: 'Which one uses more memory?' Answer: LinkedList, because it has to store two extra 'hooks' (pointers) for every single item!"


πŸ’‘ Pro Tip: "Writing code is easy. Writing efficient code is where the real skill lies!" - Anonymous


← Back: Collections Overview | Next: Sets β†’