{"record":{"id":"f7a6a8bd808a7a46","repo":"TheAlgorithms/Java","slug":"value-and-weight-arrays-must-be-of-the-same-length","errorCode":null,"errorMessage":"Value and weight arrays must be of the same length.","messagePattern":"Value and weight arrays must be of the same length\\.","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java","lineNumber":35,"sourceCode":"    }\n\n    /**\n     * Solves the 0/1 Knapsack problem using recursion.\n     *\n     * @param values   the array containing values of the items\n     * @param weights  the array containing weights of the items\n     * @param capacity the total capacity of the knapsack\n     * @param n        the number of items\n     * @return the maximum total value achievable within the given weight limit\n     * @throws IllegalArgumentException if input arrays are null, empty, or\n     *     lengths mismatch\n     */\n    public static int compute(final int[] values, final int[] weights, final int capacity, final int n) {\n        if (values == null || weights == null) {\n            throw new IllegalArgumentException(\"Input arrays cannot be null.\");\n        }\n        if (values.length != weights.length) {\n            throw new IllegalArgumentException(\"Value and weight arrays must be of the same length.\");\n        }\n        if (capacity < 0 || n < 0) {\n            throw new IllegalArgumentException(\"Invalid input: arrays must be non-empty and capacity/n \"\n                + \"non-negative.\");\n        }\n        if (n == 0 || capacity == 0 || values.length == 0) {\n            return 0;\n        }\n\n        if (weights[n - 1] <= capacity) {\n            final int include = values[n - 1] + compute(values, weights, capacity - weights[n - 1], n - 1);\n            final int exclude = compute(values, weights, capacity, n - 1);\n            return Math.max(include, exclude);\n        } else {\n            return compute(values, weights, capacity, n - 1);\n        }\n    }\n}","sourceCodeStart":17,"sourceCodeEnd":53,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java#L17-L53","documentation":"KnapsackZeroOne.compute indexes values[n-1] and weights[n-1] in the same recursion step, so the two arrays must have identical length. A mismatch would cause ArrayIndexOutOfBoundsException. The method rejects this with IllegalArgumentException upfront.","triggerScenarios":"Passing values and weights arrays that were populated independently and ended up with different element counts.","commonSituations":"Loading item data from two separate queries or files that diverge in row count; appending to one list but not the other; filtering one array without applying the same filter to the other.","solutions":["Assert values.length == weights.length before calling compute.","Build items as a single structure (e.g., a record list) and split to parallel arrays only at the call site.","If sources diverge, investigate the upstream data pipeline rather than silently trimming."],"exampleFix":"// before\nint r = KnapsackZeroOne.compute(values, weights, cap, n); // throws if lengths differ\n\n// after\nif (values.length != weights.length) {\n    throw new IllegalStateException(\"Item data corrupted: length mismatch\");\n}\nint r = KnapsackZeroOne.compute(values, weights, cap, n);","handlingStrategy":"validation","validationCode":"if (values.length != weights.length) {\n    throw new IllegalStateException(\"Values and weights arrays must match in length\");\n}\nint r = KnapsackZeroOne.compute(values, weights, capacity, n);","typeGuard":"static boolean areMatchingLengths(int[] values, int[] weights) {\n    return values != null && weights != null && values.length == weights.length;\n}","tryCatchPattern":null,"preventionTips":["Maintain items as a single collection and split to parallel arrays atomically.","Investigate upstream pipelines when array lengths diverge rather than silently trimming."],"tags":["knapsack","array-mismatch","input-validation","java"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}