Graphs

Java has no graph type. A hundred thousand vertices cost 19 MB as a list and 1,192 MB as a matrix, and that is the first decision.

10 min read🧮 Data Structures and Algorithms in Java

Java has no graph type. You build one out of the collections you already have, and which ones you choose is the first real decision in any graph problem — because the two obvious representations differ by a factor of sixty on an ordinary social graph.

The representation decision, in numbers

A hundred thousand people, about eight friends each:

plaintext
###   adjacency MATRIX: 100000 x 100000 = 10,000,000,000 cells -> 1,192 MB at 1 bit each
###   adjacency LIST:   400,000 edges -> about 19 MB
###   density: 400,000 edges out of 5,000,000,000 possible = 0.00800%

1,192 MB against 19 MB — and the matrix figure is the best possible case, one bit per cell. In Java a boolean[][] uses a byte per element, so the honest number is closer to ten gigabytes.

The last line is why. The graph uses eight thousandths of one percent of the possible edges, and a matrix reserves space for all of them. That is what "sparse" means, and almost every real graph is sparse: social networks, road maps, dependency graphs, the web.

The two representations

Adjacency list — for each vertex, the vertices it points to:

java
Map<String, List<String>> graph = new HashMap<>();
graph.computeIfAbsent("ana", k -> new ArrayList<>()).add("bo");
  • Space O(V + E). You pay for edges that exist.
  • "Who are ana's neighbours?" O(degree) — walk her list.
  • "Is ana connected to zoe?" O(degree) — scan it.

Adjacency matrix — a V × V grid, true where an edge exists:

java
boolean[][] edge = new boolean[n][n];
edge[ana][bo] = true;
  • Space O(V²), whether or not the edges exist.
  • "Is ana connected to zoe?" O(1) — one array read.
  • "Who are ana's neighbours?" O(V) — you must scan the whole row, including all the false cells.

So the rule: lists unless the graph is dense or you need constant-time edge lookup. In practice that means lists, with the exception of small graphs, and of algorithms whose inner loop is "is there an edge here" — some shortest-path and matrix-multiplication formulations genuinely want the matrix.

A third option worth knowing: an edge list, just List<Edge>. Useless for traversal and exactly right for algorithms that sort edges — Kruskal's minimum spanning tree being the standard case.

The vocabulary, and why each word changes the code

  • Directed or undirected. "Follows" is directed; "is friends with" is not. In an adjacency list an undirected edge is stored twice, once in each vertex's list — which is why the measurement above counted 400,000 entries for 200,000 friendships. Forgetting the second insert is the most common graph bug, and it presents as a traversal that mysteriously does not reach half the graph.
  • Weighted or not. A weight turns List<String> into List<Edge> with a cost on it, and it changes which algorithm is correct — breadth-first search finds the shortest path only when every edge costs the same.
  • Cyclic or acyclic. A cycle is why every traversal needs a visited set. A directed acyclic graph is a special case worth recognising, because it admits a topological sort — which is what a build tool does with your modules and what Spring does with your beans.
  • Connected or not. A graph can be several islands. An algorithm that starts at one vertex only ever sees that vertex's island, which is why "count the connected components" means starting again from every unvisited vertex.

Modelling, which is the part that is actually hard

The algorithms are standard. Recognising that you have a graph is not, and this is where the skill is:

The problemVerticesEdges
shortest routeplacesroads, weighted by time
"people you may know"peoplefriendships
build ordermodules"depends on" — a DAG
bean creationbeans"needs" — and a cycle is the error Spring reports
a state machinestatesallowed transitions
currency arbitragecurrenciesexchange rates

Two of those are worth pausing on because they are this course's own subject matter. A dependency cycle in a build is a cycle in a directed graph, and the error a build tool gives you is a cycle detection reporting its findings. So is BeanCurrentlyInCreationException — the Spring course's circular dependency is the same algorithm on a different graph.

Building one, without a library

java
class Graph {
    private final Map<String, List<String>> adjacency = new HashMap<>();
 
    void addEdge(String from, String to) {
        adjacency.computeIfAbsent(from, k -> new ArrayList<>()).add(to);
        adjacency.computeIfAbsent(to, k -> new ArrayList<>());   // so it exists as a vertex
    }
 
    List<String> neighbours(String v) {
        return adjacency.getOrDefault(v, List.of());
    }
}

Two details in those seven lines carry most of the bugs:

  • The second computeIfAbsent. Without it, a vertex with no outgoing edges is not in the map, and a traversal that reaches it gets null rather than an empty list. getOrDefault is the other half of the same defence.
  • List or Set for the neighbours. A List allows duplicate edges and preserves insertion order; a Set prevents duplicates and costs more per vertex. Which you want depends on whether "ana follows bo twice" is meaningful, and deciding it explicitly beats discovering it.

For anything substantial, use a library — JGraphT is the usual Java answer — for the same reason you do not write your own HashMap. Building one by hand is for understanding it and for interviews.

Under the hood: where the ten gigabytes actually goes, and what an adjacency list costs per edge

The matrix number in this lesson's opening — "1,192 MB at one bit each" versus "closer to ten gigabytes" as a real boolean[][] — is worth deriving rather than taking on trust, because the gap between the two is the lesson.

A boolean in a Java array is not one bit. The JVM has no sub-byte addressable storage, so boolean[] allocates one byte per element — the smallest unit memory can actually be addressed in. A hundred-thousand-by-hundred-thousand boolean[][] is a hundred thousand separate boolean[] arrays (Java has no true multidimensional array; T[][] is an array of array references), each with its own 16-byte object header on top of its hundred thousand data bytes — so the honest count is roughly 100,000 × (100,016 bytes) ≈ 10 GB, matching the lesson's figure and explaining exactly where the ideal "1 bit per cell" estimate stops being real: a BitSet-backed matrix would actually hit that ideal (one long holds 64 cells), but nobody reaches for BitSet[][] by instinct, and boolean[][] is what gets written.

The adjacency list's cost is different in kind: Map<String, List<String>> pays per vertex (a HashMap entry, as the collections lesson prices out) and per edge (one reference in an ArrayList, roughly 4 bytes with compressed oops, plus that ArrayList's own backing-array overhead). For the hundred-thousand-vertex, eight-friend graph, that is roughly 400,000 small references rather than 10 billion allocated-and-mostly-empty cells — the list representation's memory scales with what the graph actually contains, the matrix's with what it could theoretically hold regardless of density. That is the whole argument for "lists unless dense" reduced to where the bytes go.

Try it yourself

Work out where the memory actually goes

A million-vertex graph, average degree 5 (five million directed edges). Roughly compare, without running anything: an adjacency-list representation (Map<Integer, List<Integer>>, Integer boxing throughout) against a boolean[][] adjacency matrix over the same million vertices. Which one is even possible to allocate on an ordinary server, and by roughly what factor does the impossible one exceed it?

Why one of these does not fit and the other comfortably does

The matrix is 1,000,000 × 1,000,000 = one trillion cells; even at a true one-bit-per-cell packing that is 125 GB, and as a real Java boolean[][] (one byte per cell plus a million array headers) it is on the order of a terabyte — not allocatable on essentially any single machine. The adjacency list holds five million edges, each a boxed Integer reference in an ArrayList (call it roughly 20–30 bytes all-in per edge once the Integer object, the list slot, and amortised growth are counted) plus a million HashMap entries for the vertices themselves — comfortably under a gigabyte, and further reducible by using an int[]-backed adjacency structure indexed by vertex id instead of Map<Integer, List<Integer>>, which removes both the HashMap overhead and the Integer boxing entirely. The factor between "comfortably fits" and "does not fit on the machine" is not a rounding error — it is the entire reason the representation decision is the first decision in any graph problem, before any algorithm is chosen.

Misconceptions

  • "An adjacency matrix is simpler, so it is fine for a first version." It is simpler to write, but "first version" is exactly when the input size is unknown — and the matrix is the one representation whose cost is invisible at test scale (a hundred test vertices is 10,000 cells, trivial) and catastrophic at real scale (a hundred thousand vertices is ten billion), the same trap the big-O lesson names for List.contains.
  • "boolean[] in Java is a bitset, so a boolean[][] really is roughly one bit per cell." It is one byte per cell — the JVM has no addressable storage smaller than a byte — which is why the honest matrix estimate in this lesson is roughly eight times the naive "one bit per cell" figure, before even counting the per-row array headers.

Sources

  • Thomas H. Cormen et al., Introduction to Algorithms (CLRS) — graph representations, adjacency lists versus adjacency matrices, and their complexity trade-offs.
  • The Java Virtual Machine Specification, SE 21, §2.4 — the primitive types, including the storage width the JVM actually gives boolean.
  • Java Object Layout (JOL) documentation — for object-header and reference-size figures used throughout this lesson's arithmetic.
Progress is saved on this device and to your account when signed in.