Syllabus / Java / Phase 4: Collections & Error Handling (Days 17–21)
Beginner

Introduction to Collections and the List Interface

📂 Phase 4: Collections & Error Handling (Days 17–21) · Java

The Java Collections Framework is a unified architecture for storing and manipulating groups of objects — it replaces fixed-size arrays with flexible, resizable, type-safe alternatives.

The Collection Hierarchy

Iterable
  └── Collection
        ├── List   (ArrayList, LinkedList, Vector)
        ├── Set    (HashSet, LinkedHashSet, TreeSet)
        └── Queue  (PriorityQueue, ArrayDeque)

Map (HashMap, LinkedHashMap, TreeMap) — a SEPARATE hierarchy
Interview tip: Map does NOT extend Collection — it stores key-value pairs rather than single elements, which is why it sits in its own hierarchy. A frequently asked trick question.

Why Use Collections Over Arrays?

  • Dynamic resizing — no fixed size like arrays
  • Built-in methods for searching, sorting, and iterating
  • Type safety through generics (List<String> only accepts Strings)

The List Interface — Ordered, Allows Duplicates

A List is like a numbered row of seats — order matters, and the same value can appear more than once.

List fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple");  // duplicates allowed

System.out.println(fruits.get(0));  // Apple — index-based access
System.out.println(fruits.size()); // 3

ArrayList vs LinkedList

OperationArrayListLinkedList
get(index)O(1) — fast random accessO(n) — must traverse
add/remove at startO(n)O(1) — fast at the ends
Backed byDynamic arrayDoubly linked list
Rule of thumb: use ArrayList by default. Switch to LinkedList only when you're doing frequent insertions or deletions at the beginning of the list.

Common List Operations

List list = new ArrayList<>();
list.add("Java");
list.add(0, "Python");      // insert at specific index
list.remove("Java");        // remove by value
list.contains("Python");    // true
list.size();                // 1

for (String item : list) {  // for-each iteration
    System.out.println(item);
}