Storing graphs in Java
28 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Representing graphs in Java involves choosing between adjacency matrices, adjacency lists, and edge lists depending on density.
Adjacency matrix representation
An adjacency list stores a graph as a list of neighbours for every node; it uses O(V + E) space and is the usual choice for sparse graphs.
An adjacency matrix is a V by V grid: matrix[u][v] is 1 when an edge joins u to v, otherwise 0. Checking for an edge takes O(1) time, but the matrix always uses O(V^2) space.
Example 1 · Building and Querying an Adjacency Matrix
public class Main { static class GraphMatrix { int[][] matrix; GraphMatrix(int n) { matrix = new int[n][n]; }
void addEdge(int u, int v) { matrix[u][v] = 1; matrix[v][u] = 1; // Undirected }
boolean hasEdge(int u, int v) { return matrix[u][v] == 1; } }
public static void main(String[] args) { GraphMatrix g = new GraphMatrix(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(2, 3);
System.out.println("Edge 0-1 exists: " + g.hasEdge(0, 1)); System.out.println("Edge 1-3 exists: " + g.hasEdge(1, 3)); }}Edge 0-1 exists: true Edge 1-3 exists: false
What this code does
- matrix size is 4x4, initialized to zeros.
- addEdge sets symmetric entries matrix[u][v] and matrix[v][u] to 1.
- hasEdge checks edge presence in instant O(1) time.
In an undirected graph the matrix is symmetric across the diagonal. For a weighted graph, matrix[u][v] stores the weight.
Listing all neighbours of u scans a whole row, which costs O(V).
Adjacency list representation using List<List<Integer>>
An adjacency list stores a list of neighbour lists, commonly initialized as List<List<Integer>> in Java. Index u contains an inner list storing only vertices directly connected to u. In undirected graphs, an edge between u and v is added to both adj.get(u) and adj.get(v).
Example 2 · Building an Adjacency List in Java
import java.util.ArrayList;import java.util.List;
public class Main { public static void main(String[] args) { int n = 4; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
int[][] edges = {{0, 1}, {0, 2}, {1, 2}, {2, 3}}; for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
for (int i = 0; i < n; i++) { System.out.println("Neighbors of " + i + ": " + adj.get(i)); } }}Neighbors of 0: [1, 2] Neighbors of 1: [0, 2] Neighbors of 2: [0, 1, 3] Neighbors of 3: [2]
What this code does
- adj list is instantiated with n empty inner lists.
- Undirected edges add connections to both endpoint neighbour lists.
- Printing adj.get(i) iterates only existing neighbours in O(degree) time.
An adjacency list consumes O(V + E) memory for directed graphs and O(V + 2E) for undirected graphs. Iterating over all neighbours of vertex u takes optimal O(degree(u)) time. Because most real-world graphs are sparse where E is small, adjacency lists are the standard choice.
Fix the error
Pick the line that compiles
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Create an adjacency list: one list of neighbours for each vertex.
Error
AdjFix.java:5: error: generic array creation
List<Integer>[] adj = new ArrayList<Integer>[3];
^Edge list and choosing the right representation
An edge list is a flat collection of pairs, int[][] edges with rows [u, v] or [u, v, weight]. Algorithms that look at all edges at once, such as Kruskal's, use it.
Example 3 · Weighted Graph Adjacency List with Edge Objects
import java.util.ArrayList;import java.util.List;
public class Main { static class Edge { int to, weight; Edge(int to, int weight) { this.to = to; this.weight = weight; } }
public static void main(String[] args) { int n = 3; List<List<Edge>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
// Edge [u, v, weight] int[][] edgeData = {{0, 1, 15}, {1, 2, 25}}; for (int[] e : edgeData) { adj.get(e[0]).add(new Edge(e[1], e[2])); }
for (int i = 0; i < n; i++) { for (Edge e : adj.get(i)) { System.out.println(i + " -> " + e.to + " (Weight: " + e.weight + ")"); } } }}0 -> 1 (Weight: 15) 1 -> 2 (Weight: 25)
What this code does
- Edge class encapsulates the destination vertex and numeric weight.
- Outer list maps source vertex to its outgoing directed edges.
- Traversal accesses connected weights directly without 2D matrix overhead.
Choose an adjacency matrix for dense graphs, where the edge count approaches V^2 and instant edge lookups matter. Choose an adjacency list for sparse graphs and for BFS and DFS. Choose an edge list when sorting all edges by weight.
Next step
Check your understanding
10 quick questions