TheAlgorithms/Java · error · IllegalArgumentException
Key must not be null
Error message
Key must not be null
What it means
Thrown by LIFOCache.get(K) when the key is null. The cache is HashMap-backed and null keys would collide with the absent-entry contract; the guard runs before lock acquisition and before any eviction-strategy or statistics updates. LIFOCache is the LIFO (stack-based) sibling of FIFOCache and shares the same null-key policy.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/caches/LIFOCache.java:120
this.evictionListener = builder.evictionListener;
this.evictionStrategy = builder.evictionStrategy;
}
/**
* Retrieves the value associated with the specified key from the cache.
*
* <p>If the key is not present or the corresponding entry has expired, this method
* returns {@code null}. If an expired entry is found, it will be removed and the
* eviction listener (if any) will be notified. Cache hit-and-miss statistics are
* also updated accordingly.
*
* @param key the key whose associated value is to be returned; must not be {@code null}
* @return the cached value associated with the key, or {@code null} if not present or expired
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public V get(K key) {
if (key == null) {
throw new IllegalArgumentException("Key must not be null");
}
lock.lock();
try {
evictionStrategy.onAccess(this);
final CacheEntry<V> entry = cache.get(key);
if (entry == null || entry.isExpired()) {
if (entry != null) {
cache.remove(key);
keys.remove(key);
notifyEviction(key, entry.value);
}
misses++;
return null;
}
hits++;
return entry.value;View on GitHub (pinned to fdfb9a395b)
Solutions
- Null-check the key before lookup, returning a default upstream.
- Use Optional.ofNullable(key).map(cache::get).orElse(null).
- Validate at the service boundary.
Example fix
// before V v = cache.get(request.getKey()); // after K k = request.getKey(); if (k == null) return defaultValue; return cache.get(k);
Defensive patterns
Strategy: validation
Validate before calling
if (key == null) return defaultValue; V value = cache.get(key);
Type guard
static <K> boolean isLookupKey(K key) {
return key != null;
} Prevention
- Validate request parameters at the controller before they reach the cache.
- Centralize lookups in a helper returning Optional.
- Never pipe Map.get() output straight into cache.get().
When it happens
Trigger: cache.get(null); cache.get(map.get(absentKey)) yielding null; lookups driven by unvalidated user input.
Common situations: Request parameters mapped straight to cache keys; optional deserialized fields; migrating from a tolerant cache implementation.
Related errors
- Key and value must not be null
- Key cannot be null
- Listener must not be null
- Eviction strategy must not be null
- Key must not be null
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/caaf4ef3efb8d86a.
Report an issue: GitHub.