{"record":{"id":"be0556b6b562fcef","repo":"TheAlgorithms/Java","slug":"cannot-insert-null-into-the-heap","errorCode":null,"errorMessage":"Cannot insert null into the heap.","messagePattern":"Cannot insert null into the heap\\.","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java","lineNumber":23,"sourceCode":"\n/**\n * A generic implementation of a max heap data structure.\n *\n * @param <T> the type of elements in this heap, must extend Comparable.\n */\npublic class GenericHeap<T extends Comparable<T>> {\n\n    private final ArrayList<T> data = new ArrayList<>();\n    private final HashMap<T, Integer> map = new HashMap<>();\n\n    /**\n     * Adds an item to the heap, maintaining the heap property.\n     *\n     * @param item the item to be added\n     */\n    public void add(T item) {\n        if (item == null) {\n            throw new IllegalArgumentException(\"Cannot insert null into the heap.\");\n        }\n\n        this.data.add(item);\n        map.put(item, this.data.size() - 1);\n        upHeapify(this.data.size() - 1);\n    }\n\n    /**\n     * Restores the heap property by moving the item at the given index upwards.\n     *\n     * @param ci the index of the current item\n     */\n    private void upHeapify(int ci) {\n        int pi = (ci - 1) / 2;\n        if (ci > 0 && isLarger(this.data.get(ci), this.data.get(pi)) > 0) {\n            swap(pi, ci);\n            upHeapify(pi);\n        }","sourceCodeStart":5,"sourceCodeEnd":41,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java#L5-L41","documentation":"Thrown by GenericHeap.add(T) when item is null. The heap maintains a HashMap<T,Integer> index and relies on Comparable ordering during upHeapify, both of which break on null (compareTo would NPE and the map cannot key null safely). Rejecting null at the boundary gives a clear message instead of a later NullPointerException.","triggerScenarios":"Calling add(null) directly; passing the result of Map.get(key) that returned null; iterating a collection that contains null elements and forwarding them to add().","commonSituations":"Uninitialized fields defaulting to null; Optional.orElse(null) piped into the heap; deserialization or JSON parsing that yields null slots.","solutions":["Filter nulls out of the source collection before adding each element.","Replace null with a meaningful default/sentinel value, or skip the element conditionally.","Fix the upstream producer so it never emits null (return Optional and handle absence explicitly)."],"exampleFix":"// before\nheap.add(map.get(maybeMissingKey));\n\n// after\nT v = map.get(maybeMissingKey);\nif (v != null) heap.add(v);","handlingStrategy":"type-guard","validationCode":"T item = produceItem();\nif (item != null) {\n    heap.add(item);\n}","typeGuard":"// Java has no type guard for nullability at compile time; use explicit null check.\n// If using Optional:\nOptional<T> opt = Optional.ofNullable(produceItem());\nopt.ifPresent(heap::add);","tryCatchPattern":null,"preventionTips":["Filter nulls from source collections before iterating into add().","Avoid Optional.orElse(null); prefer ifPresent or orElseThrow with a meaningful value.","Annotate with @Nonnull and enable static null-analysis in your IDE/build."],"tags":["heap","null-check","precondition","generic-heap"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}