Sobes.tech
Junior — Middle

What data structure is suitable for implementing a basic caching mechanism?

sobes.tech AI

Answer from AI

For the basic caching mechanism in Java, the data structure LinkedHashMap is often used. It allows storing key-value pairs and maintains the insertion order or access order, which is convenient for implementing policies like removing old elements (e.g., LRU — Least Recently Used).

Example of a simple cache with size limit:

import java.util.LinkedHashMap;
import java.util.Map;

public class SimpleCache<K, V> extends LinkedHashMap<K, V> {
    private final int maxEntries;

    public SimpleCache(int maxEntries) {
        super(maxEntries + 1, 1.0f, true); // true for access order
        this.maxEntries = maxEntries;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > maxEntries;
    }
}

This cache automatically removes the oldest element when exceeding the maximum size.