How to use generics to write an LRU cache in Java?

  Implementing an LRU (Least Recently Used) cache in Java can use generics to flexibly support different types of data. The LRU cache is based on the recent access policy. When the cache reaches a certain size, the least recently used data item will be removed from the cache.

  The following is an implementation example of a simple LRU cache using generics, and I will explain its core parts step by step.

import java.util.*;

public class LRUCache<K, V> {
    private final int capacity;
    private final LinkedHashMap<K, V> cache;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new LinkedHashMap<>(capacity, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > capacity;
            }
        };
    }

    public V get(K key) {
        return cache.getOrDefault(key, null);
    }

    public void put(K key, V value) {
        cache.put(key, value);
    }

    public void display() {
        for (Map.Entry<K, V> entry : cache.entrySet()) {
            System.out.print("(" + entry.getKey() + ":" + entry.getValue() + ") ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        LRUCache<String, Integer> cache = new LRUCache<>(3);
        cache.put("one", 1);
        cache.put("two", 2);
        cache.put("three", 3);

        System.out.println("Initial Cache:");
        cache.display(); // Output: (one:1) (two:2) (three:3)

        cache.get("one"); // Access "one" to make it most recently used.

        System.out.println("Cache after accessing 'one':");
        cache.display(); // Output: (two:2) (three:3) (one:1)

        cache.put("four", 4); // Adding a new item, which should remove the least recently used item ("two").

        System.out.println("Cache after adding 'four':");
        cache.display(); // Output: (three:3) (one:1) (four:4)
    }
}

  Next, the author explains the above code step by step:

  1. The LRUCache class is a generic class that accepts two type parameters K and V, representing the type of key and value respectively.

  2. In the constructor, we pass in the capacity of the cache (the maximum number of key-value pairs allowed to be stored). We use LinkedHashMap to implement cache because it can keep insertion order or access order, we choose access order to implement LRU strategy.

  3. When constructing LinkedHashMap, we set accessOrder to true by passing parameters, which will move the visited elements to the end of the linked list so that we can easily find the most recently used elements.

  4. We also override the removeEldestEntry method, which will be called after adding a new element. Here we check if the size of the cache exceeds capacity, and if so, remove the oldest element. This method determines when to remove the least frequently used elements.

  5. The get method allows to get the value in the cache, and returns null if the key does not exist.

  6. The put method is used to add key-value pairs to the cache.

  7. The display method is used to display the cached content for debugging and testing.

  8. In the main method, we demonstrate how to create an LRUCache instance and use it to add, get and update elements in the cache.

  The above example demonstrates how to write an LRU cache using generics. We can extend and customize it according to our needs.

おすすめ

転載: blog.csdn.net/Blue92120/article/details/132618776