TheAlgorithms/Java · error · IllegalArgumentException

Weights and values must be non-null and of the same length.

Error message

Weights and values must be non-null and of the same length.

What it means

The 0/1 Knapsack DP algorithm requires parallel arrays: weights[i] and values[i] describe the same item. throwIfInvalidInput rejects null arrays or arrays of unequal length with IllegalArgumentException, because a length mismatch would cause an ArrayIndexOutOfBoundsException inside the DP loop.

Source

Thrown at src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java:37

 * Output: 220
 *
 * @author Arpita
 * @see <a href="https://en.wikipedia.org/wiki/Knapsack_problem">Knapsack Problem</a>
 */
public final class Knapsack {

    private Knapsack() {
    }

    /**
     * Validates the input to ensure correct constraints.
     */
    private static void throwIfInvalidInput(final int weightCapacity, final int[] weights, final int[] values) {
        if (weightCapacity < 0) {
            throw new IllegalArgumentException("Weight capacity should not be negative.");
        }
        if (weights == null || values == null || weights.length != values.length) {
            throw new IllegalArgumentException("Weights and values must be non-null and of the same length.");
        }
        if (Arrays.stream(weights).anyMatch(w -> w <= 0)) {
            throw new IllegalArgumentException("Weights must be positive.");
        }
    }

    /**
     * Solves the 0/1 Knapsack problem using Dynamic Programming (bottom-up approach).
     *
     * @param weightCapacity The maximum weight capacity of the knapsack.
     * @param weights        The array of item weights.
     * @param values         The array of item values.
     * @return The maximum total value achievable without exceeding capacity.
     */
    public static int knapSack(final int weightCapacity, final int[] weights, final int[] values) {
        throwIfInvalidInput(weightCapacity, weights, values);

        int[] dp = new int[weightCapacity + 1];

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Assert weights.length == values.length and both are non-null before the call.
  2. Build weights and values as a single List<Item> and split into parallel arrays atomically.
  3. If one source is incomplete, trim both arrays to the shorter length (after confirming correctness).

Example fix

// before
int best = Knapsack.knapSack(cap, weights, values); // throws if lengths differ

// after
if (weights == null || values == null || weights.length != values.length) {
    throw new IllegalStateException("Bad item data");
}
int best = Knapsack.knapSack(cap, weights, values);
Defensive patterns

Strategy: validation

Validate before calling

if (weights == null || values == null || weights.length != values.length) {
    throw new IllegalStateException("Invalid knapsack input arrays");
}
int best = Knapsack.knapSack(weightCapacity, weights, values);

Type guard

static boolean areValidItemArrays(int[] weights, int[] values) {
    return weights != null && values != null && weights.length == values.length;
}

Prevention

When it happens

Trigger: Passing weights and values arrays of different lengths, or passing null for either array. Common when arrays are built independently or sourced from separate columns.

Common situations: Loading weights and values from separate database queries that return different row counts; appending to one array but not the other; deserializing a malformed payload where one field is missing.

Related errors


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