TheAlgorithms/Java · error · IllegalArgumentException

Key cannot be null

Error message

Key cannot be null

What it means

Thrown by LIFOCache.removeKey(K) when the key is null. Removal touches both the HashMap and the keys stack; a null key is rejected up front to keep the contract symmetric with get/put. The check precedes lock acquisition.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/caches/LIFOCache.java:238

                it.remove();
                cache.remove(k);
                notifyEviction(k, entry.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");
        }
        lock.lock();
        try {
            final CacheEntry<V> entry = cache.remove(key);
            keys.remove(key);

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

            notifyEviction(key, entry.value);
            return entry.value;
        } finally {
            lock.unlock();
        }
    }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Null-check before removing: if (key != null) cache.removeKey(key);
  2. Filter nulls from the key collection 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)) yielding null; invalidation loops containing null.

Common situations: Invalidation fed by optional IDs; event payloads with unset key fields; tests passing null.

Related errors


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