TheAlgorithms/Java · error · IllegalArgumentException

Number of vertices must be positive

Error message

Number of vertices must be positive

What it means

Thrown by the Graph constructor in BoruvkaAlgorithm when the vertex count is negative. The constructor guards `vertex < 0` before allocating the graph, so a negative value is rejected up front. Note the message says 'positive' but the guard only blocks negatives, so 0 passes this check (it fails later during edge validation).

Source

Thrown at src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java:47

        }
    }

    /**
     * Represents the graph
     */
    static class Graph {
        final int vertex;
        final List<Edge> edges;

        /**
         * Constructor for the graph
         *
         * @param vertex number of vertices
         * @param edges  list of edges
         */
        Graph(final int vertex, final List<Edge> edges) {
            if (vertex < 0) {
                throw new IllegalArgumentException("Number of vertices must be positive");
            }
            if (edges == null || edges.isEmpty()) {
                throw new IllegalArgumentException("Edges list must not be null or empty");
            }
            for (final var edge : edges) {
                checkEdgeVertices(edge.src, vertex);
                checkEdgeVertices(edge.dest, vertex);
            }

            this.vertex = vertex;
            this.edges = edges;
        }
    }

    /**
     * Represents a subset for Union-Find operations
     */
    private static class Component {

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Clamp/validate the vertex count to be non-negative before constructing the Graph
  2. Trace where `vertex` originates and fix the upstream computation (e.g. guard empty inputs before `list.size() - 1`)
  3. Pass an explicit positive literal once input parsing is confirmed correct

Example fix

// before
Graph g = new BoruvkaAlgorithm.Graph(n - 1, edges);
// after
if (n < 1) throw new IllegalArgumentException("need >=1 vertex");
Graph g = new BoruvkaAlgorithm.Graph(n, edges);
Defensive patterns

Strategy: validation

Validate before calling

if (vertex < 0) {
    throw new IllegalArgumentException("vertex must be >= 0, got " + vertex);
}

Try / catch

try {
    new BoruvkaAlgorithm.Graph(v, edges);
} catch (IllegalArgumentException e) {
    // handle invalid vertex count
}

Prevention

When it happens

Trigger: Constructing `new BoruvkaAlgorithm.Graph(vertex, edges)` where `vertex` is a negative int, e.g. a count derived from `list.size() - 1` on an empty list, or read from malformed input/config.

Common situations: Reading vertex counts from user input or files where the value is -1/missing; off-by-one when computing counts; parse errors that yield negatives.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/f8b53057a8324c99. Report an issue: GitHub.