TheAlgorithms/Java · error · IllegalArgumentException
Self-loops are not allowed
Error message
Self-loops are not allowed
What it means
Thrown by `WelshPowell.Graph.addEdge` when both endpoints are equal (`nodeA == nodeB`). Welsh-Powell graph coloring assumes a simple graph; a self-loop has no meaningful color assignment, so it is rejected. Vertices are validated for bounds first, then the self-loop check runs.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java:64
throw new IllegalArgumentException("Number of vertices cannot be negative");
}
adjacencyLists = new HashSet[vertices];
Arrays.setAll(adjacencyLists, i -> new HashSet<>());
}
/**
* Adds an edge between two vertices in the graph.
*
* @param nodeA one end of the edge
* @param nodeB the other end of the edge
* @throws IllegalArgumentException if the vertices are out of bounds or if a self-loop is attempted
*/
private void addEdge(int nodeA, int nodeB) {
validateVertex(nodeA);
validateVertex(nodeB);
if (nodeA == nodeB) {
throw new IllegalArgumentException("Self-loops are not allowed");
}
adjacencyLists[nodeA].add(nodeB);
adjacencyLists[nodeB].add(nodeA);
}
/**
* Validates that the vertex index is within the bounds of the graph.
*
* @param vertex the index of the vertex to validate
* @throws IllegalArgumentException if the vertex is out of bounds
*/
private void validateVertex(int vertex) {
if (vertex < 0 || vertex >= getNumVertices()) {
throw new IllegalArgumentException("Vertex " + vertex + " is out of bounds");
}
}
/**View on GitHub (pinned to fdfb9a395b)
Solutions
- Filter out self-loop edges `[v, v]` before calling makeGraph
- Fix the data source so endpoints differ
- If self-loops are meaningful in your model, use a graph type that supports them
Example fix
// before
int[][] edges = {{0, 0}, {0, 1}};
// after (removed self-loop)
int[][] edges = {{0, 1}}; Defensive patterns
Strategy: validation
Validate before calling
for (int[] e : edges) {
if (e[0] == e[1]) {
throw new IllegalArgumentException("self-loop at " + e[0]);
}
} Try / catch
try {
WelshPowell.makeGraph(n, edges);
} catch (IllegalArgumentException e) {
// self-loop or bad vertex
} Prevention
- Sanitize edge data to remove self-loops before construction
- Validate symmetry/diagonal entries when importing adjacency data
When it happens
Trigger: Calling `makeGraph` with an edge `[v, v]`, or `addEdge(v, v)` directly — both endpoints identical.
Common situations: Data where a vertex is accidentally linked to itself (diagonal in an adjacency source); un-deduplicated edge endpoints; off-by-one that makes two distinct values coincide.
Related errors
- Number of vertices cannot be negative
- Vertex {vertex} is out of bounds
- Edge array must have exactly two elements
- Number of vertices must be positive
- Edges list must not be null or empty
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/81e46100b994c631.
Report an issue: GitHub.