TheAlgorithms/Java · error · IllegalArgumentException

Capacity must be greater than 0!

Error message

Capacity must be greater than 0!

What it means

Thrown by MRUCache.checkCapacity() when the cache is constructed with a capacity of zero or less. MRUCache requires at least one slot. Unlike LRUCache, this correctly uses IllegalArgumentException, making it catchable by type.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java:66

     */
    private void setCapacity(int newCapacity) {
        checkCapacity(newCapacity);
        while (data.size() > newCapacity) {
            Entry<K, V> evicted = evict();
            data.remove(evicted.getKey());
        }
        this.cap = newCapacity;
    }

    /**
     * Checks if the specified capacity is valid.
     *
     * @param capacity the capacity to check
     * @throws IllegalArgumentException if the capacity is less than or equal to zero
     */
    private void checkCapacity(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException("Capacity must be greater than 0!");
        }
    }

    /**
     * Evicts the most recently used entry from the cache.
     *
     * @return the evicted entry
     * @throws RuntimeException if the cache is empty
     */
    private Entry<K, V> evict() {
        if (head == null) {
            throw new RuntimeException("Cache cannot be empty!");
        }
        final Entry<K, V> evicted = this.tail;
        tail = evicted.getPreEntry();
        if (tail != null) {
            tail.setNextEntry(null);
        }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Ensure the capacity value is >= 1 before constructing the cache
  2. Validate configuration values at startup
  3. Use the no-arg constructor if you only need the default capacity of 100

Example fix

// before
MRUCache<String,String> cache = new MRUCache<>(props.getInt("cache.max"));

// after
int cap = props.getInt("cache.max", 100);
if (cap <= 0) cap = 100;
MRUCache<String,String> cache = new MRUCache<>(cap);
Defensive patterns

Strategy: validation

Validate before calling

if (cap < 1) {
    throw new IllegalStateException("MRUCache capacity must be >= 1, got: " + cap);
}
MRUCache<String,String> cache = new MRUCache<>(cap);

Try / catch

try {
    cache = new MRUCache<>(cap);
} catch (IllegalArgumentException e) {
    logger.error("Invalid MRUCache capacity: " + cap, e);
    cache = new MRUCache<>(); // default 100
}

Prevention

When it happens

Trigger: Calling new MRUCache(0), new MRUCache(-5), or passing any int <= 0 to the MRUCache(int cap) constructor. The no-arg constructor defaults to 100.

Common situations: Capacity sourced from a config file or environment variable that can be 0 or unset. Deriving capacity from arithmetic that can produce a non-positive result.

Related errors


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