Skip to content

Module 9 · Collections and Generics — topic 1 of 5

The Collections Framework

An overview of the Collection interfaces and their main implementations, choosing the right collection, immutable collections, and the Collections utility class.

Beginner 14 min read·Lesson 30 of 39 in Java Programming

Learning objectives

  • Name the core collection interfaces and what each guarantees
  • Choose an implementation by its ordering and performance
  • Use immutable factory methods and the Collections utility class

Definition

The Java Collections Framework is a set of interfaces (Collection, List, Set, Queue, Deque, Map) and implementations (ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, ArrayDeque, PriorityQueue and others) for storing and processing groups of objects.

Introduction

Arrays have a fixed size and few built-in operations. Real programs need groups of data that grow, shrink, stay sorted, reject duplicates or answer 'what is the value for this key?' quickly. The Collections Framework provides a well-designed toolbox for all of these, and it is used in practically every Java program.

Why it matters

Picking the right collection is often the difference between a program that is instant and one that is unusably slow.

Collections questions — HashMap internals, ArrayList vs LinkedList — are among the most common Java interview topics.

Detailed explanation

List — an ordered sequence with indexes that allows duplicates. ArrayList (resizable array: fast random access, fast append) is the default; LinkedList is rarely better in practice.

Set — no duplicates. HashSet (fast, no order), LinkedHashSet (keeps insertion order), TreeSet (sorted, O(log n)).

Map — key-to-value pairs with unique keys (not a subtype of Collection). HashMap (fast, no order), LinkedHashMap (insertion order), TreeMap (sorted keys).

Queue and Deque — ArrayDeque works as both a FIFO queue (offer/poll) and a LIFO stack (push/pop), and is preferred over the legacy Stack class. PriorityQueue always gives you the smallest element first (a min-heap).

Program to interfaces. Declare variables with the interface type — List<String> names = new ArrayList<>(); — so you can switch implementations without changing other code.

Immutable collections (Java 9+). List.of(...), Set.of(...) and Map.of(...) create compact unmodifiable collections; List.copyOf makes an unmodifiable copy. Modifying them throws UnsupportedOperationException, and they don't allow null elements.

java.util.Collections offers static helpers: sort, reverse, shuffle, max, min, frequency, unmodifiableList, nCopies and emptyList.

Collections hold objects only, so primitives are autoboxed (List<Integer>).

Syntax

Java
List<String> names = new ArrayList<>(); // ordered, duplicates allowed
Set<String> tags = new HashSet<>(); // unique, unordered
Map<String, Integer> stock = new HashMap<>(); // key -> value
Deque<Integer> stack = new ArrayDeque<>(); // stack or queue
Queue<Integer> pq = new PriorityQueue<>(); // smallest first
List<String> fixed = List.of("a", "b"); // unmodifiable
  • The diamond <> lets the compiler infer the type arguments.
  • HashMap/HashSet need correct equals and hashCode; TreeMap/TreeSet need comparable elements or a Comparator.
  • Most collections are not thread-safe; see java.util.concurrent for shared use.

Code examples

One task, four collections

Java
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] words = {"pear", "apple", "fig", "apple", "kiwi", "fig"};
List<String> list = new ArrayList<>(Arrays.asList(words));
Set<String> hashSet = new HashSet<>(list);
Set<String> linked = new LinkedHashSet<>(list);
Set<String> sorted = new TreeSet<>(list);
System.out.println("List: " + list + " size " + list.size());
System.out.println("HashSet size: " + hashSet.size() + " (order not guaranteed)");
System.out.println("LinkedHashSet: " + linked);
System.out.println("TreeSet: " + sorted);
System.out.println("frequency of apple: " + Collections.frequency(list, "apple") + ", max: " + Collections.max(list));
}
}
Output
List:          [pear, apple, fig, apple, kiwi, fig] size 6
HashSet size:  4 (order not guaranteed)
LinkedHashSet: [pear, apple, fig, kiwi]
TreeSet:       [apple, fig, kiwi, pear]
frequency of apple: 2, max: pear

Stacks, queues and priority queues

Java
import java.util.*;
public class Main {
public static void main(String[] args) {
Deque<String> stack = new ArrayDeque<>();
stack.push("page1"); stack.push("page2"); stack.push("page3");
System.out.println("back from " + stack.pop() + " to " + stack.peek());
Queue<String> line = new ArrayDeque<>();
line.offer("Asha"); line.offer("Ravi"); line.offer("Meera");
System.out.println("serving " + line.poll() + ", next " + line.peek() + ", waiting " + line.size());
Queue<Integer> tasks = new PriorityQueue<>(List.of(5, 1, 4, 2, 3));
StringBuilder order = new StringBuilder();
while (!tasks.isEmpty()) order.append(tasks.poll()).append(' ');
System.out.println("by priority: " + order.toString().trim());
}
}
Output
back from page3 to page2
serving Asha, next Ravi, waiting 2
by priority: 1 2 3 4 5

More examples

Immutability, views and performance

Java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> fixed = List.of("C", "Java", "Python");
try {
fixed.add("Go");
} catch (UnsupportedOperationException e) {
System.out.println("List.of is unmodifiable");
}
List<String> backing = new ArrayList<>(fixed);
List<String> view = Collections.unmodifiableList(backing);
backing.add("Go");
System.out.println("view sees backing changes: " + view);
int n = 200_000;
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) { list.add(i); set.add(i); }
long t0 = System.nanoTime();
int hitsList = 0;
for (int i = n - 1000; i < n; i++) if (list.contains(i)) hitsList++;
long t1 = System.nanoTime();
int hitsSet = 0;
for (int i = n - 1000; i < n; i++) if (set.contains(i)) hitsSet++;
long t2 = System.nanoTime();
System.out.println("found " + hitsList + " and " + hitsSet + "; HashSet lookups faster: " + (t2 - t1 < t1 - t0));
Map<String, List<String>> byLetter = new TreeMap<>();
for (String w : List.of("banana", "avocado", "blueberry", "apple", "cherry"))
byLetter.computeIfAbsent(w.substring(0, 1), k -> new ArrayList<>()).add(w);
System.out.println(byLetter);
}
}
Output
List.of is unmodifiable
view sees backing changes: [C, Java, Python, Go]
found 1000 and 1000; HashSet lookups faster: true
{a=[avocado, apple], b=[banana, blueberry], c=[cherry]}

Step-by-step explanation

  • List.of creates an unmodifiable list, so add throws UnsupportedOperationException.
  • Collections.unmodifiableList is a read-only *view*: callers can't modify it, but changes to the backing list show through.
  • list.contains scans the ArrayList element by element (O(n)), while set.contains hashes straight to the right bucket (O(1) on average); with 200,000 elements the difference is dramatic.
  • computeIfAbsent creates the inner list the first time a letter is seen, then add appends the word — a standard grouping pattern.
  • The TreeMap prints its keys in sorted order, while each list keeps the order in which the words were added.

Expected output

Running “Immutability, views and performance” prints exactly:

TextOutput
List.of is unmodifiable
view sees backing changes: [C, Java, Python, Go]
found 1000 and 1000; HashSet lookups faster: true
{a=[avocado, apple], b=[banana, blueberry], c=[cherry]}

Practical applications

  • HashMap for caches, lookups by id and counting
  • ArrayList for most ordered data shown to users
  • ArrayDeque for undo stacks and BFS queues
  • PriorityQueue for schedulers and Dijkstra's algorithm

Best practices

  • Default to ArrayList, HashMap and HashSet; choose Linked/Tree variants when you need their ordering.
  • Use List.of/Set.of/Map.of for fixed data.
  • Use ArrayDeque instead of Stack and LinkedList for stacks and queues.

Common mistakes

Declaring with the implementation type

Avoid

ArrayList<String> names = new ArrayList<>();

Prefer

List<String> names = new ArrayList<>();

Using the interface keeps code flexible and makes it easy to swap implementations.

Using List.contains for frequent lookups

Avoid

List<String> seen = new ArrayList<>();
if (!seen.contains(id)) seen.add(id);

Prefer

Set<String> seen = new HashSet<>();
seen.add(id); // returns false if already present

contains on a list is linear, making the whole loop quadratic; a HashSet makes each check constant time.

Important notes

  • HashSet and HashMap iteration order is unspecified and may differ between Java versions — never rely on it.
  • Vector, Stack and Hashtable are legacy synchronised classes; avoid them in new code.

Key takeaways

  • List = ordered with duplicates; Set = unique; Map = key to value; Deque = stack or queue.
  • Choose implementations by ordering needs and performance.
  • Program to interfaces and use immutable factories for fixed data.

Try it yourself

  1. 1
    Remove duplicates from a list of names while keeping their original order.
  2. 2
    Use an ArrayDeque to check whether brackets in a string such as "{[()]}" are balanced.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

3 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhich collection does not allow duplicate elements?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this topic