{"record":{"id":"24f3cb129905ee0e","repo":"TheAlgorithms/Java","slug":"median-is-undefined-for-an-empty-data-set","errorCode":null,"errorMessage":"Median is undefined for an empty data set.","messagePattern":"Median is undefined for an empty data set\\.","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"warning","filePath":"src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java","lineNumber":47,"sourceCode":"    public final void insert(final T element) {\n        if (!minHeap.isEmpty() && element.compareTo(minHeap.peek()) < 0) {\n            maxHeap.offer(element);\n            balanceHeapsIfNeeded();\n        } else {\n            minHeap.offer(element);\n            balanceHeapsIfNeeded();\n        }\n    }\n\n    /**\n     * Returns the median of the current elements.\n     *\n     * @return the median value\n     * @throws IllegalArgumentException if no elements have been inserted\n     */\n    public final T getMedian() {\n        if (maxHeap.isEmpty() && minHeap.isEmpty()) {\n            throw new IllegalArgumentException(\"Median is undefined for an empty data set.\");\n        }\n\n        if (maxHeap.size() == minHeap.size()) {\n            return calculateAverage(maxHeap.peek(), minHeap.peek());\n        }\n\n        return (maxHeap.size() > minHeap.size()) ? maxHeap.peek() : minHeap.peek();\n    }\n\n    /**\n     * Calculates the average between two values.\n     * Concrete subclasses must define how averaging works (e.g., for Integer, Double, etc.).\n     *\n     * @param a first number\n     * @param b second number\n     * @return the average of a and b\n     */\n    protected abstract T calculateAverage(T a, T b);","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java#L29-L65","documentation":"Thrown by MedianOfRunningArray.getMedian when both internal heaps are empty, i.e., insert() has never been called. The class maintains a two-heap median structure (max-heap for the lower half, min-heap for the upper half); with no elements there is no defined median. It is an abstract generic class parameterized by a Number type.","triggerScenarios":"Constructing a MedianOfRunningArray subclass and calling getMedian() before any insert(element). Also when all inserted elements were conceptually cleared (though no clear method exists in the base class).","commonSituations":"Calling getMedian on a freshly created tracker before the stream starts, or a streaming job where the first window had no events yet.","solutions":["Track an insertion count (or check a flag) and skip/return a sentinel until at least one element is inserted.","Ensure at least one insert() precedes the first getMedian() call in your flow.","If an empty median is meaningful in your domain, branch before getMedian and return null/Optional.empty."],"exampleFix":"// before\nMedianOfRunningArray<Integer> med = new MedianOfRunningArrayInteger();\nInteger m = med.getMedian(); // throws\n\n// after\nMedianOfRunningArray<Integer> med = new MedianOfRunningArrayInteger();\nOptional<Integer> m = med.isEmpty()\n    ? Optional.empty()\n    : Optional.of(med.getMedian());","handlingStrategy":"validation","validationCode":"// MedianOfRunningArray has no isEmpty() in base; track insertions yourself\nboolean hasData = insertedCount > 0;\nT median = hasData ? tracker.getMedian() : null;","typeGuard":null,"tryCatchPattern":"try {\n    T m = tracker.getMedian();\n} catch (IllegalArgumentException e) {\n    // no data inserted yet; treat as no median available\n    return Optional.empty();\n}","preventionTips":["Maintain a counter of insert() calls and guard getMedian with it.","In streaming jobs, only compute the median after the first window has data."],"tags":["median","streaming","precondition","heap","statistics"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}