Map 可以用来实现缓存,具体实现如下:

import java.util.HashMap;
import java.util.Map;

public class Cache<K, V> {

    private final Map<K, V> cache;

    public Cache() {
        this.cache = new HashMap<>();
    }

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

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

    public boolean contains(K key) {
        return cache.containsKey(key);
    }

    public void clear() {
        cache.clear();
    }

    public int size() {
        return cache.size();
    }

    public boolean isEmpty() {
        return cache.isEmpty();
    }

}

使用示例:

public static void main(String[] args) {
    Cache<String, Integer> cache = new Cache<>();

    cache.put("a", 1);
    cache.put("b", 2);
    cache.put("c", 3);

    System.out.println(cache.get("a")); // 1
    System.out.println(cache.contains("d")); // false

    cache.clear();
    System.out.println(cache.size()); // 0
}

在上面的示例中,我们使用了 HashMap 来实现缓存,put 方法用于添加数据,get 方法用于获取数据,contains 方法用于判断缓存是否包含某个 key,clear 方法用于清空缓存,sizeisEmpty 方法用于获取缓存大小和判断缓存是否为空。

map实现缓存

原文地址: https://www.cveoy.top/t/topic/bKT0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录