Create A Graph In Java Through Lists

2 min read

Creating a graph in Java through lists usually means using an adjacency list: each vertex stores a list of the vertices connected to it. This approach is memory-efficient, easy to extend, and suitable for implementing networks, routes, dependencies, social connections, recommendation systems, and many other relationship-based problems It's one of those things that adds up..

Introduction

A graph is a data structure made up of vertices (also called nodes) and edges (connections between vertices). To give you an idea, cities can be represented as vertices while roads between them are edges. If movement is allowed in only one direction, the graph is directed. If every connection works in both directions, it is undirected.

Java does not provide a built-in graph class in its standard collection framework, so developers commonly create one using arrays, linked lists, maps, or a combination of these structures. An adjacency list is often the best starting point because it stores only existing connections rather than reserving space for every possible pair of vertices.

Choosing an Adjacency List Representation

Assume a graph has five vertices numbered from 0 to 4. Its adjacency list might look like this:

0 → 1 → 3
1 → 2
2 → 4
3 → 2
4 → 0

This representation means that vertex 0 connects to vertices 1 and 3, vertex 1 connects to vertex 2, and so on. Internally, the outer list contains one entry per vertex, while each inner list contains that vertex’s neighbors Worth keeping that in mind..

The basic type can therefore be written as:

List> adjacencyList;

The outer list represents all vertices, and each inner List<Integer> represents the edges leaving one vertex.

Steps to Create a Graph in Java Through Lists

1. Define the Graph Class

Start by creating a class that stores the adjacency list. The constructor initializes one empty list for every vertex It's one of those things that adds up. That's the whole idea..

import java.util.ArrayList;
import java.util.List;

public class Graph {
    private final List> adjacencyList;

    public Graph(int vertexCount) {
        if (vertexCount < 0) {
            throw new IllegalArgumentException("Vertex count cannot be negative.");
        }

        adjacencyList = new ArrayList<>(vertexCount);

        for (int i = 0; i < vertexCount; i++) {
            adjacencyList.add(new ArrayList<>());
        }
    }

    public int vertexCount() {
        return adjacencyList.size();
    }

    public List neighbors(int vertex) {
        validateVertex(vertex);
        return new ArrayList<>(adjacencyList.get(vertex));
    }

    private void validateVertex(int vertex) {
        if (vertex < 0 || vertex >= adjacencyList.size()) {
            throw new IllegalArgumentException("Invalid vertex: " + vertex);
        }
    }
}

Returning a copy from neighbors() protects the internal structure from accidental modification by external code That's the part that actually makes a difference..

2. Add Vertices and Edges

Vertices are created by the constructor. An edge is added by placing a destination vertex inside the source vertex’s list.

New In

Recently Written

If You're Into This

Similar Reads

Thank you for reading about Create A Graph In Java Through Lists. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home