Skip to main content

Java Collections

Collections Overview

Complete lesson for Collections Overview using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Collections Overview

Section: Java Collections. The java.util collection hierarchy: List, Set, Queue, Map, complexity, and fail-fast iterators.

The two roots

  • Collection is the root of lists, sets, and queues. Map is a separate hierarchy (key-value, not a Collection).
  • Iterable lets you use for-each. Iterator is the cursor (hasNext / next / remove).
  • Program to interfaces: declare List, Set, Map, Deque — construct ArrayList, HashSet, HashMap, ArrayDeque.
InterfaceDuplicatesOrderCommon impls
ListYesInsertion (positional)ArrayList, LinkedList
SetNoDependsHashSet, LinkedHashSet, TreeSet
Queue / DequeYesFIFO / both endsArrayDeque, LinkedList, PriorityQueue
MapUnique keysDependsHashMap, LinkedHashMap, TreeMap, ConcurrentHashMap

Complexity cheat sheet (amortized / average)

Typeget / containsaddNotes
ArrayListget O(1); contains O(n)amortized O(1) at endRandomAccess; slow mid insert
LinkedListget O(n)O(1) at endsNode overhead; implements Deque
HashSet / HashMapaverage O(1)average O(1)Needs equals/hashCode; no order
TreeSet / TreeMapO(log n)O(log n)Sorted; Comparable or Comparator
ArrayDequeN/AO(1) at endsBest default Stack/Queue
PriorityQueuepeek O(1)offer O(log n)Heap; not a sorted list

Fail-fast vs fail-safe

  • Most java.util iterators are **fail-fast**: if the collection is structurally modified except via Iterator.remove, they throw ConcurrentModificationException.
  • This is *best-effort*, even on a single thread — a for-each plus list.add is enough.
  • ConcurrentHashMap iterators are weakly consistent (no CME for concurrent writes). CopyOnWriteArrayList snapshots on iterate.
import java.util.ArrayList;
import java.util.List;

public class CollectionsOverview {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("ada");
        names.add("linus");
        for (String n : names) {
            System.out.println(n);
        }
        System.out.println(names.size());
    }
}
L2

Advanced — Collections Overview

Contracts and interview mistakes

  • hashCode/equals must be consistent or HashSet/HashMap lose keys. Mutable keys are a famous bug.
  • Comparable natural order must be consistent with equals for TreeSet/TreeMap or you get “duplicate” keys that equals says are equal.
  • The Collections Framework is not thread-safe by default. Wrap with Collections.synchronizedList or use concurrent types.
  • null: HashMap allows one null key; ConcurrentHashMap, Hashtable, and TreeMap (with natural order) do not.
L3

Tricky Interview Points

Q1) Is Map a Collection?

Answer No. Map is a separate interface. You can view keys/values/entries as collections via keySet, values, entrySet.

Q2) List vs Set?

Answer List is ordered and allows duplicates and index access. Set forbids duplicates (by equals/hashCode or compare) and has no index.

Q3) What is fail-fast?

Answer An iterator that detects structural modification (via a modCount) and throws ConcurrentModificationException. It is not a reliable concurrency mechanism.

Q4) Why declare List instead of ArrayList?

Answer You can swap implementations (ArrayList vs LinkedList vs unmodifiable List.of) without changing callers.

Q5) Which collection is sorted?

Answer TreeSet and TreeMap (red-black tree). LinkedHashSet/Map keep insertion order but are not sorted by value.

Q6) How do you iterate a Map?

Answer for (var e : map.entrySet()), forEach, or keySet/values. Prefer entrySet to avoid extra lookups.

L4

Simple Programs

Pick a collection by need

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ChooseCollection {
    public static void main(String[] args) {
        List<String> tickets = new ArrayList<>();
        tickets.add("T1");
        tickets.add("T1");
        Set<String> unique = new HashSet<>(tickets);
        Map<String, Integer> freq = new HashMap<>();
        for (String t : tickets) {
            freq.merge(t, 1, Integer::sum);
        }
        System.out.println(unique);
        System.out.println(freq);
    }
}
L5

Problem Solving Tricks

  • List.of / Set.of / Map.of (Java 9+) are unmodifiable and reject null.
  • Need both uniqueness and insertion order? LinkedHashSet / LinkedHashMap.
  • Need thread safety and a map? ConcurrentHashMap, not a synchronized HashMap, for most cases.
  • Measure before switching ArrayList to LinkedList — LinkedList is almost never faster in real JVMs.
L6

Practice Programs List

  1. Store names in a List, unique names in a Set, and counts in a Map — same input.
  2. Trigger ConcurrentModificationException by adding inside for-each, then fix with an Iterator or removeIf.
  3. Write a method that accepts Collection and works for both List and Set.
  4. Compare HashSet vs TreeSet iteration order on the same integers.
  5. Explain from memory which implementations allow null.