TheAlgorithms/Java · error · IllegalArgumentException

Points array cannot be empty

Error message

Points array cannot be empty

What it means

Thrown by the KDTree(Point[]) constructor when the points array has length 0. The constructor reads points[0].getDimension() to infer k, so an empty array would ArrayIndexOutOfBoundsException. The IllegalArgumentException rejects an empty input before any dimension inference.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/trees/KDTree.java:38

    private final int k; // Dimensions of the points

    /**
     * Constructor for empty KDTree
     *
     * @param k Number of dimensions
     */
    KDTree(int k) {
        this.k = k;
    }

    /**
     * Builds the KDTree from the specified points
     *
     * @param points Array of initial points
     */
    KDTree(Point[] points) {
        if (points.length == 0) {
            throw new IllegalArgumentException("Points array cannot be empty");
        }
        this.k = points[0].getDimension();
        for (Point point : points) {
            if (point.getDimension() != k) {
                throw new IllegalArgumentException("Points must have the same dimension");
            }
        }
        this.root = build(points, 0);
    }

    /**
     * Builds the KDTree from the specified coordinates of the points
     *
     * @param pointsCoordinates Array of initial points coordinates
     *
     */
    KDTree(int[][] pointsCoordinates) {
        if (pointsCoordinates.length == 0) {

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Skip KDTree construction when the point set is empty; handle the empty case separately.
  2. Ensure at least one point is present before calling the constructor.
  3. Use Optional or an explicit empty-state branch in the caller.
  4. Validate collection size at the input boundary.

Example fix

// before
KDTree tree = new KDTree(points);
// after
if (points.length == 0) {
    return Optional.empty();
}
KDTree tree = new KDTree(points);
Defensive patterns

Strategy: validation

Validate before calling

if (points.length > 0) {
    KDTree tree = new KDTree(points);
} else {
    // handle empty point set
}

Prevention

When it happens

Trigger: Constructing a KDTree from an empty collection converted to an array. Passing a points array built by filtering that yielded no matches. Passing a test fixture with no points.

Common situations: Dynamic point sets that can be empty after filtering. Deserialization of an empty dataset. Pipeline stages where an upstream filter removed all points.

Related errors


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