{"record":{"id":"171a1531ab18b99f","repo":"TheAlgorithms/Java","slug":"weights-and-values-must-be-non-null-and-of-the-sam","errorCode":null,"errorMessage":"Weights and values must be non-null and of the same length.","messagePattern":"Weights and values must be non-null and of the same length\\.","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java","lineNumber":37,"sourceCode":" * Output: 220\n *\n * @author Arpita\n * @see <a href=\"https://en.wikipedia.org/wiki/Knapsack_problem\">Knapsack Problem</a>\n */\npublic final class Knapsack {\n\n    private Knapsack() {\n    }\n\n    /**\n     * Validates the input to ensure correct constraints.\n     */\n    private static void throwIfInvalidInput(final int weightCapacity, final int[] weights, final int[] values) {\n        if (weightCapacity < 0) {\n            throw new IllegalArgumentException(\"Weight capacity should not be negative.\");\n        }\n        if (weights == null || values == null || weights.length != values.length) {\n            throw new IllegalArgumentException(\"Weights and values must be non-null and of the same length.\");\n        }\n        if (Arrays.stream(weights).anyMatch(w -> w <= 0)) {\n            throw new IllegalArgumentException(\"Weights must be positive.\");\n        }\n    }\n\n    /**\n     * Solves the 0/1 Knapsack problem using Dynamic Programming (bottom-up approach).\n     *\n     * @param weightCapacity The maximum weight capacity of the knapsack.\n     * @param weights        The array of item weights.\n     * @param values         The array of item values.\n     * @return The maximum total value achievable without exceeding capacity.\n     */\n    public static int knapSack(final int weightCapacity, final int[] weights, final int[] values) {\n        throwIfInvalidInput(weightCapacity, weights, values);\n\n        int[] dp = new int[weightCapacity + 1];","sourceCodeStart":19,"sourceCodeEnd":55,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java#L19-L55","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Assert weights.length == values.length and both are non-null before the call.","Build weights and values as a single List<Item> and split into parallel arrays atomically.","If one source is incomplete, trim both arrays to the shorter length (after confirming correctness)."],"exampleFix":"// before\nint best = Knapsack.knapSack(cap, weights, values); // throws if lengths differ\n\n// after\nif (weights == null || values == null || weights.length != values.length) {\n    throw new IllegalStateException(\"Bad item data\");\n}\nint best = Knapsack.knapSack(cap, weights, values);","handlingStrategy":"validation","validationCode":"if (weights == null || values == null || weights.length != values.length) {\n    throw new IllegalStateException(\"Invalid knapsack input arrays\");\n}\nint best = Knapsack.knapSack(weightCapacity, weights, values);","typeGuard":"static boolean areValidItemArrays(int[] weights, int[] values) {\n    return weights != null && values != null && weights.length == values.length;\n}","tryCatchPattern":null,"preventionTips":["Build weights and values from a single list of item objects to guarantee parallel arrays.","Add a data-integrity assertion at the ingestion boundary."],"tags":["knapsack","array-mismatch","null-check","input-validation","java"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}