TheAlgorithms/Java · error · IllegalArgumentException

Values and weights arrays must be non-null and of same lengt

Error message

Values and weights arrays must be non-null and of same length.

What it means

KnapsackZeroOneTabulation.compute iterates items in parallel over values and weights, populating dp[i][w]. The two arrays must have the same length to avoid an ArrayIndexOutOfBoundsException. The method rejects a length mismatch with IllegalArgumentException before allocating the DP table.

Source

Thrown at src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java:41

    private KnapsackZeroOneTabulation() {
        // Prevent instantiation
    }

    /**
     * Solves the 0-1 Knapsack problem using the bottom-up tabulation technique.
     * @param values the values of the items
     * @param weights the weights of the items
     * @param capacity the total capacity of the knapsack
     * @param itemCount the number of items
     * @return the maximum value that can be put in the knapsack
     * @throws IllegalArgumentException if input arrays are null, of different lengths,or if capacity or itemCount is invalid
     */
    public static int compute(final int[] values, final int[] weights, final int capacity, final int itemCount) {
        if (values == null || weights == null) {
            throw new IllegalArgumentException("Values and weights arrays must not be null.");
        }
        if (values.length != weights.length) {
            throw new IllegalArgumentException("Values and weights arrays must be non-null and of same length.");
        }
        if (capacity < 0) {
            throw new IllegalArgumentException("Capacity must not be negative.");
        }
        if (itemCount < 0 || itemCount > values.length) {
            throw new IllegalArgumentException("Item count must be between 0 and the length of the values array.");
        }

        final int[][] dp = new int[itemCount + 1][capacity + 1];

        for (int i = 1; i <= itemCount; i++) {
            final int currentValue = values[i - 1];
            final int currentWeight = weights[i - 1];

            for (int w = 1; w <= capacity; w++) {
                if (currentWeight <= w) {
                    final int includeItem = currentValue + dp[i - 1][w - currentWeight];
                    final int excludeItem = dp[i - 1][w];

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Assert values.length == weights.length before calling compute.
  2. Maintain items as a single collection of (value, weight) pairs and split atomically.
  3. Add a data-integrity check at the ingestion boundary.

Example fix

// before
int r = KnapsackZeroOneTabulation.compute(values, weights, cap, count); // throws

// after
assert values.length == weights.length : "item arrays must match";
int r = KnapsackZeroOneTabulation.compute(values, weights, cap, count);
Defensive patterns

Strategy: validation

Validate before calling

if (values.length != weights.length) {
    throw new IllegalStateException("Values and weights arrays must match in length");
}
int r = KnapsackZeroOneTabulation.compute(values, weights, capacity, itemCount);

Type guard

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

Prevention

When it happens

Trigger: Passing values and weights arrays of different lengths — from independent data sources, partial updates, or a filter applied to one array but not the other.

Common situations: Loading items from two CSV columns that have mismatched row counts; appending an item to values but forgetting weights; deserializing a payload where one array field is truncated.

Related errors


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