Java Collections Overview

Introduction

Arrays have fixed size. Collections are dynamic structures for groups of objects—lists, sets, and maps. This chapter maps the Java Collections Framework (JCF) so later chapters (ArrayList, HashMap, HashSet) fit into one mental model. Use with Generics and Interfaces.

Prerequisites

Why Collections Exist

NeedTypical choice
Ordered list, allow duplicatesListArrayList
Unique elements, no order guaranteeSetHashSet
Lookup by keyMapHashMap
Fixed size, primitives fast patharray

Framework Hierarchy (Simplified)

text
Iterable<T>
    └── Collection<E>
            ├── List<E>     — ordered, duplicates OK
            ├── Set<E>      — unique elements
            └── Queue<E>    — FIFO processing (awareness)
 
Map<K, V>  — separate hierarchy (key → value)

Common implementations:

InterfaceImplementationNotes
ListArrayListdynamic array, fast random access
ListLinkedListfast insert/remove at ends
SetHashSethash table, no order
SetTreeSetsorted set
MapHashMaphash table by key
MapTreeMapsorted by keys

1) Iterable and Collection

Iterable provides iterator() / for-each support.

Collection adds:

  • add, remove, contains
  • size, isEmpty
  • clear
java
Collection<String> names = new ArrayList<>();
names.add("Emma");
names.add("Liam");
System.out.println(names.size());

Program to interface types when possible:

java
List<String> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Map<String, Integer> map = new HashMap<>();

2) List — Ordered Sequence

  • Allows duplicates
  • Access by index
  • Deep dive: ArrayList

3) Set — Unique Elements

  • No duplicate elements (by equals / hashCode)
  • Deep dive: HashSet

4) Map — Key-Value Pairs

  • Not a Collection, but core to JCF
  • Keys unique; one value per key
  • Deep dive: HashMap

5) Generics with Collections

java
List<String> words = new ArrayList<>();
Map<String, Integer> scores = new HashMap<>();

Avoid raw types:

java
List raw = new ArrayList();  // legacy — no compile-time checks

6) Arrays vs Collections

ArrayArrayList
Sizefixedgrows
Primitivesyes (int[])uses wrappers (Integer)
Performanceexcellent for simple storageflexible API
Utility sortArrays.sortCollections.sort / streams

Convert between them:

java
List<String> list = new ArrayList<>(List.of("a", "b"));
String[] arr = list.toArray(new String[0]);
List<String> back = new ArrayList<>(Arrays.asList(arr));

7) Choosing an Implementation (Quick Guide)

  • Default list → ArrayList
  • Remove duplicates → HashSet
  • Name → score lookup → HashMap
  • Need sorted keys/values → TreeMap / TreeSet (later)

Common Beginner Mistakes

Confusing List and ArrayList

List is the interface; ArrayList is one implementation.

Expecting HashSet to Keep Insertion Order

Use LinkedHashSet if insertion order matters (awareness).

Using null Keys in HashMap Carelessly

One null key allowed in HashMap; avoid unless you understand rules.

What’s Next

ArrayListHashMap → exercises 3739.

FAQ

Are collections thread-safe by default?

No. ArrayList, HashMap, HashSet are not. Use concurrent collections or synchronization in multithreaded code (Multithreading).

When still use arrays?

Performance-critical primitive buffers, matrices, APIs returning arrays.

What is Collections utility class?

Static helpers: sort, reverse, max, unmodifiableList, etc.

Do collections work with streams?

Yes—collection.stream() pipelines (Functional Programming).

Immutable collections?

List.of(), Set.of(), Map.of() create fixed-size immutable collections (Java 9+).