{"record":{"id":"0e0a3656f93342fe","repo":"TheAlgorithms/Java","slug":"sample-size-cannot-exceed-stream-size","errorCode":null,"errorMessage":"Sample size cannot exceed stream size.","messagePattern":"Sample size cannot exceed stream size\\.","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/randomized/ReservoirSampling.java","lineNumber":36,"sourceCode":" * @see <a href=\"https://en.wikipedia.org/wiki/Reservoir_sampling\">Reservoir Sampling - Wikipedia</a>\n */\npublic final class ReservoirSampling {\n\n    // Prevent instantiation of utility class\n    private ReservoirSampling() {\n        throw new UnsupportedOperationException(\"Utility class\");\n    }\n\n    /**\n     * Selects k random elements from a stream using reservoir sampling.\n     *\n     * @param stream     The input stream as an array of integers.\n     * @param sampleSize The number of elements to sample.\n     * @return A list containing k randomly selected elements.\n     */\n    public static List<Integer> sample(int[] stream, int sampleSize) {\n        if (sampleSize > stream.length) {\n            throw new IllegalArgumentException(\"Sample size cannot exceed stream size.\");\n        }\n\n        List<Integer> reservoir = new ArrayList<>(sampleSize);\n        Random rand = new Random();\n\n        for (int i = 0; i < stream.length; i++) {\n            if (i < sampleSize) {\n                reservoir.add(stream[i]);\n            } else {\n                int j = rand.nextInt(i + 1);\n                if (j < sampleSize) {\n                    reservoir.set(j, stream[i]);\n                }\n            }\n        }\n\n        return reservoir;\n    }","sourceCodeStart":18,"sourceCodeEnd":54,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/randomized/ReservoirSampling.java#L18-L54","documentation":"Thrown by ReservoirSampling.sample(stream, sampleSize) when sampleSize > stream.length. The algorithm fills the reservoir with the first sampleSize elements, so requesting more than the stream has is invalid. NOTE: this is the ONLY guard — a null stream throws NPE elsewhere, and a negative sampleSize passes this check but later throws IllegalArgumentException from ArrayList(-1) capacity.","triggerScenarios":"sample(new int[]{1,2,3}, 5) (sampleSize 5 > length 3); computing sampleSize from a percentage that rounds up beyond the stream size.","commonSituations":"Asking for k=10 samples from a stream of 7; user-configured sample count larger than the available data; percentage-based sampling (sampleSize = ceil(pct * n)) that exceeds n.","solutions":["Cap sampleSize to stream.length before calling: sampleSize = Math.min(sampleSize, stream.length).","If you need exactly sampleSize elements, ensure your stream has at least that many upstream.","Also guard stream != null and sampleSize >= 0 at the caller — the method does not."],"exampleFix":"// before\nList<Integer> s = ReservoirSampling.sample(stream, k); // k may exceed stream.length\n\n// after\nint k = Math.min(requestedK, stream == null ? 0 : stream.length);\nList<Integer> s = ReservoirSampling.sample(stream, k);","handlingStrategy":"validation","validationCode":"if (stream == null) throw new IllegalArgumentException(\"stream must not be null\");\nif (sampleSize < 0) throw new IllegalArgumentException(\"sampleSize must be >= 0\");\nint k = Math.min(sampleSize, stream.length);\nList<Integer> s = ReservoirSampling.sample(stream, k);","typeGuard":"static boolean validReservoirParams(int[] stream, int sampleSize) {\n    return stream != null && sampleSize >= 0 && sampleSize <= stream.length;\n}","tryCatchPattern":"try {\n    List<Integer> s = ReservoirSampling.sample(stream, sampleSize);\n} catch (IllegalArgumentException | NullPointerException e) {\n    logger.warn(\"Reservoir sampling rejected stream/sampleSize\");\n}","preventionTips":["Cap sampleSize to stream.length before calling.","Also guard stream != null and sampleSize >= 0 — the method checks neither.","Watch percentage-based sample sizes that can round up beyond the stream size."],"tags":["randomized","input-validation","illegal-argument","reservoir-sampling","sampling"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}