JAVA - Zero to Hero / Collection Framework

List Interface (ArrayList, LinkedList)

📄 List Interface (ArrayList, LinkedList)

The List interface in Java is part of the Collections Framework and represents an ordered collection. It allows duplicate elements and maintains the insertion order.


🧩 Key Features of List:

  • Maintains insertion order

  • Allows duplicates

  • Index-based access

  • Supports dynamic resizing


🚀 Common Implementations

Class

Backing Structure

Access Time

Insert/Delete Time

Use Case

ArrayList

Dynamic Array

✅ Fast (O(1))

❌ Slow (O(n))

Frequent access

LinkedList

Doubly Linked List

❌ Slow (O(n))

✅ Fast (O(1) at ends)

Frequent insertions/deletions


✅ Example 1: ArrayList

import java.util.ArrayList;

public class Example {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        System.out.println(fruits);

        fruits.remove("Banana");
        System.out.println(fruits);
    }
}
[Apple, Banana, Mango]
[Apple, Mango]

✅ Example 2: LinkedList

import java.util.LinkedList;

public class Example {
    public static void main(String[] args) {
        LinkedList<Integer> numbers = new LinkedList<>();

        numbers.add(10);
        numbers.add(20);
        numbers.addFirst(5);   // Add at beginning
        numbers.addLast(30);   // Add at end

        System.out.println(numbers);
    }
}
[5, 10, 20, 30]

⚖️ Summary: ArrayList vs LinkedList

Feature

ArrayList

LinkedList

Order Maintained?

✅ Yes

✅ Yes

Allows Duplicates?

✅ Yes

✅ Yes

Access Speed

🔥 Fast (O(1))

🐢 Slow (O(n))

Insert/Delete

🐢 Slow (O(n))

⚡ Fast at ends (O(1))

Best Use Case

Read-heavy apps

Insert/delete-heavy apps