TheAlgorithms/Java · error · IllegalArgumentException

Key cannot be null

Error message

Key cannot be null

What it means

Thrown by FIFOCache.removeKey(K) when the key is null. Removal uses the underlying HashMap.remove, and a null key is rejected to keep the contract symmetric with get/put. The check precedes lock acquisition, so a rejected removal leaves cache state unchanged.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/caches/FIFOCache.java:231

            if (entry != null && entry.getValue().isExpired()) {
                it.remove();
                notifyEviction(entry.getKey(), entry.getValue().value);
                count++;
            }
        }

        return count;
    }

    /**
     * Removes the specified key and its associated entry from the cache.
     *
     * @param key the key to remove from the cache;
     * @return the value associated with the key;  or {@code null} if no such key exists
     */
    public V removeKey(K key) {
        if (key == null) {
            throw new IllegalArgumentException("Key cannot be null");
        }
        CacheEntry<V> entry = cache.remove(key);

        // No such key in cache
        if (entry == null) {
            return null;
        }

        notifyEviction(key, entry.value);
        return entry.value;
    }

    /**
     * Notifies the eviction listener, if one is registered, that a key-value pair has been evicted.
     *
     * <p>If the {@code evictionListener} is not {@code null}, it is invoked with the provided key
     * and value. Any exceptions thrown by the listener are caught and logged to standard error,
     * preventing them from disrupting cache operations.

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Null-check the key before removing: if (key != null) cache.removeKey(key);
  2. Filter nulls out of the collection of keys to invalidate before iterating.
  3. Validate keys at the event-ingestion boundary.

Example fix

// before
for (K k : keys) cache.removeKey(k);
// after
for (K k : keys) { if (k != null) cache.removeKey(k); }
Defensive patterns

Strategy: validation

Validate before calling

if (key != null) cache.removeKey(key);

Type guard

static <K> boolean isRemovableKey(K key) {
    return key != null;
}

Prevention

When it happens

Trigger: cache.removeKey(null); cache.removeKey(map.get(absentKey)) where the inner lookup yields null; cleanup loops driven by a collection that contains null.

Common situations: Invalidation routines fed by optional IDs; event handlers where the payload key field is unset; tests that pass null to assert behavior.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/1d66c4c5157ac05b. Report an issue: GitHub.