Collections Overview in Java

A complete guide to the Java Collections Framework: its hierarchy, core interfaces, implementations, and when to choose each one.

The Java Collections Framework (JCF) is a unified architecture for storing and manipulating groups of objects. It ships as part of java.util and provides ready-made data structures — lists, sets, queues, and maps — along with algorithms such as sorting and searching that work across all of them. Before the JCF arrived in Java 1.2, developers had to write their own data structures or use unrelated classes like Vector and Hashtable, which had no common interface. Understanding the framework is essential both for writing efficient Java code and for performing well in technical interviews.

Why the Collections Framework Exists

Arrays have a fixed size and no built-in algorithms. Early Java shipped Vector and Hashtable, but they were designed independently, synchronised unconditionally, and could not be swapped for one another. The JCF solved this by defining a set of interfaces that describe behaviour, and providing multiple implementations you can swap without changing calling code. You program to the interface (List, Set, Queue, Map) and choose the concrete class (ArrayList, HashSet, ArrayDeque, HashMap) based on your access patterns.

The Core Hierarchy

The framework splits into two independent hierarchies.

Collection Hierarchy

Iterable
  └── Collection
        ├── List        (ordered, index-based, allows duplicates)
        │     ├── ArrayList
        │     ├── LinkedList
        │     └── Vector  ← legacy
        │           └── Stack  ← legacy
        ├── Set         (no duplicates)
        │     ├── HashSet
        │     ├── LinkedHashSet
        │     └── SortedSet → NavigableSet → TreeSet
        └── Queue       (FIFO ordering by default)
              ├── LinkedList
              ├── PriorityQueue
              └── Deque (double-ended queue)
                    ├── ArrayDeque
                    └── LinkedList

Map Hierarchy (separate from Collection)

Map
  ├── HashMap
  ├── LinkedHashMap
  ├── Hashtable  ← legacy
  └── SortedMap → NavigableMap → TreeMap

Map does not extend Collection because a map holds key-value pairs, not individual elements.

Key Interfaces at a Glance

Interface Ordering Duplicates Null Thread-safe
List Insertion order Yes Yes (most) No (use CopyOnWriteArrayList)
Set Depends on impl. No One null (HashSet) No (use CopyOnWriteArraySet)
Queue FIFO / priority Yes No (most) No (use ConcurrentLinkedQueue)
Deque Both ends Yes No No (use ConcurrentLinkedDeque)
Map Depends on impl. Keys: No / Values: Yes Depends No (use ConcurrentHashMap)

Choosing the Right Implementation

Need Best choice
Ordered list, fast random access ArrayList
Fast insert/remove at both ends ArrayDeque
FIFO queue ArrayDeque
Stack (LIFO) ArrayDeque
Unique elements, fast lookup HashSet
Unique elements, insertion order LinkedHashSet
Unique elements, sorted TreeSet
Priority-based processing PriorityQueue
Key-value, fast lookup HashMap
Key-value, insertion order LinkedHashMap
Key-value, sorted keys TreeMap
Thread-safe key-value ConcurrentHashMap

Example: Programming to the Interface

import java.util.ArrayList;
import java.util.List;

public class InterfaceExample {
    // Accept List, not ArrayList — easy to swap implementations
    public static void printAll(List<String> items) {
        for (String item : items) {
            System.out.println(item);
        }
    }

    public static void main(String[] args) {
        List<String> languages = new ArrayList<>();
        languages.add("Java");
        languages.add("Python");
        languages.add("Go");
        printAll(languages);
        // Output:
        // Java
        // Python
        // Go
    }
}

Example: Using the Collections Utility Class

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsUtility {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9, 3));

        System.out.println("Max: " + Collections.max(numbers));   // 9
        System.out.println("Min: " + Collections.min(numbers));   // 1

        Collections.sort(numbers);
        System.out.println("Sorted: " + numbers);                 // [1, 2, 3, 5, 8, 9]

        Collections.reverse(numbers);
        System.out.println("Reversed: " + numbers);               // [9, 8, 5, 3, 2, 1]

        Collections.shuffle(numbers);
        System.out.println("Shuffled: " + numbers);               // random order
    }
}

Common Mistakes

  • Using legacy classes in new code. Vector, Stack, and Hashtable are synchronised on every operation. In new code, use ArrayList, ArrayDeque, and HashMap (or their concurrent counterparts) instead.
  • Declaring variables as concrete types. Writing ArrayList<String> list = new ArrayList<>() instead of List<String> list = new ArrayList<>() prevents you from swapping implementations without changing call sites.
  • Confusing Collections and Collection. Collection is the interface; Collections (plural) is a utility class with static helper methods like sort, shuffle, and unmodifiableList.
  • Modifying a collection while iterating. Adding or removing elements inside a for-each loop throws ConcurrentModificationException. Use an Iterator with iterator.remove(), or collect changes and apply them after the loop.
  • Assuming Map is part of Collection. Map is a separate hierarchy. Methods like size() and isEmpty() exist on both, but Map does not implement Collection.

Best Practices

  • Always declare variables using the most general interface that satisfies your needs (List, Set, Queue, Map).
  • Prefer ArrayList as your default list and HashMap as your default map unless you have a specific reason to choose otherwise.
  • Use List.of(), Set.of(), and Map.of() (Java 9+) to create small, immutable collections.
  • For concurrent access, use the java.util.concurrent classes (ConcurrentHashMap, CopyOnWriteArrayList) rather than Collections.synchronizedXxx wrappers.
  • Initialise collections with a known capacity when you have a good estimate of the final size to avoid unnecessary resize operations.

Interview Questions

1. What is the Java Collections Framework?

The JCF is a unified set of interfaces and implementations in java.util for storing and manipulating groups of objects. It provides consistent APIs across lists, sets, queues, and maps, along with utility algorithms in the Collections class. It replaced the ad-hoc pre-Java-1.2 classes (Vector, Hashtable) and removed the need to write custom data structures.

2. What is the difference between Collection and Collections?

Collection (no s) is a root interface in the hierarchy that List, Set, and Queue extend. Collections (with s) is a final utility class with only static methods such as sort(), binarySearch(), reverse(), and unmodifiableList().

3. Why doesn't Map extend Collection?

Map stores key-value pairs, not individual elements. The Collection contract requires elements to be single objects. Forcing Map to implement Collection would require arbitrary decisions about whether to iterate over keys, values, or entries, which would make the contract ambiguous.

4. When would you use LinkedHashSet over HashSet?

Use LinkedHashSet when you need uniqueness (no duplicates) AND want to preserve insertion order during iteration. HashSet gives no ordering guarantee. LinkedHashSet achieves this by maintaining a doubly-linked list alongside the hash table, at the cost of slightly more memory.

5. What is the difference between fail-fast and fail-safe iterators?

Fail-fast iterators (used by ArrayList, HashMap, etc.) throw ConcurrentModificationException if the collection is structurally modified after the iterator was created. Fail-safe iterators (used by CopyOnWriteArrayList, ConcurrentHashMap) operate on a snapshot or a lock-free structure and do not throw; they may not reflect the latest state.

6. How do you make a collection unmodifiable?

Use Collections.unmodifiableList(list) (and similar wrappers), or prefer the factory methods List.of(), Set.of(), Map.of() (Java 9+) which return truly immutable collections. The unmodifiable wrappers prevent mutation through the returned reference but the underlying collection can still be modified directly.

7. What is the time complexity of common collection operations?

ArrayList: get(i) O(1), add at end amortized O(1), add/remove at index O(n). LinkedList: get(i) O(n), add/remove at ends O(1). HashSet/HashMap: add/contains/get O(1) average, O(n) worst case. TreeSet/TreeMap: all operations O(log n). PriorityQueue: offer/poll O(log n), peek O(1).

Summary

  • The Java Collections Framework provides interfaces (List, Set, Queue, Deque, Map) and concrete implementations so you can choose the right data structure for each problem.
  • Always program to the interface, not the implementation.
  • Vector, Stack, and Hashtable are legacy classes; prefer their modern equivalents in new code.
  • The Collections utility class provides static algorithms (sort, shuffle, search) that work on any Collection.
  • Understanding time complexities and thread-safety characteristics of each implementation is a frequent interview topic.

Continue Learning

Next: Iterable

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.