TheAlgorithms/Java · error · IllegalArgumentException

Matrix must contain at least one element.

Error message

Matrix must contain at least one element.

What it means

Thrown by MedianOfMatrix.median when, after iterating all rows and skipping null rows, the flattened list is empty. The median of zero elements is undefined, so the method refuses rather than throwing IndexOutOfBoundsException on Collections.sort / get. Note: a matrix whose every row is null also lands here, since flattened stays empty.

Source

Thrown at src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java:26

 * Median of Matrix (https://medium.com/@vaibhav.yadav8101/median-in-a-row-wise-sorted-matrix-901737f3e116)
 * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
 */

public final class MedianOfMatrix {
    private MedianOfMatrix() {
    }

    public static int median(Iterable<List<Integer>> matrix) {
        List<Integer> flattened = new ArrayList<>();

        for (List<Integer> row : matrix) {
            if (row != null) {
                flattened.addAll(row);
            }
        }

        if (flattened.isEmpty()) {
            throw new IllegalArgumentException("Matrix must contain at least one element.");
        }

        Collections.sort(flattened);
        return flattened.get((flattened.size() - 1) / 2);
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check that the matrix has at least one non-empty, non-null row before calling.
  2. Guard with a flattened-size check and return a domain 'no median' value (e.g., OptionalInt.empty()).
  3. Filter out null/empty rows upstream so the matrix is always non-trivial.

Example fix

// before
int med = MedianOfMatrix.median(matrix);

// after
boolean hasElements = false;
for (List<Integer> row : matrix) {
    if (row != null && !row.isEmpty()) { hasElements = true; break; }
}
if (!hasElements) throw new NoSuchElementException("matrix has no elements");
int med = MedianOfMatrix.median(matrix);
Defensive patterns

Strategy: validation

Validate before calling

boolean hasElements = false;
for (List<Integer> row : matrix) {
    if (row != null && !row.isEmpty()) { hasElements = true; break; }
}
if (!hasElements) throw new NoSuchElementException("matrix has no elements");
int med = MedianOfMatrix.median(matrix);

Prevention

When it happens

Trigger: Call median with an empty Iterable, an Iterable of all-null rows, or a matrix whose non-null rows are all empty lists.

Common situations: A sparse matrix representation with all-null rows, filtering that removed every row, JSON deserialization yielding empty inner lists, or an iterator over a query result with no rows.

Related errors


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