import java.util.HashMap; import java.util.Map; public class Cache { // 用 HashMap 存储缓存数据 private final Map cache; // 构造方法:初始化缓存 public Cache() { cache = new HashMap<>(); } // 存入缓存 public void put(K key, V value) { cache.put(key, value); } // 从缓存读取 public V get(K key) { return cache.get(key); } // 判断缓存是否存在某个 key public boolean containsKey(K key) { return cache.containsKey(key); } // 移除缓存 public void remove(K key) { cache.remove(key); } // 清空缓存 public void clear() { cache.clear(); } // 获取缓存大小 public int size() { return cache.size(); } // 测试 main 方法 public static void main(String[] args) { Cache studentScore = new Cache<>(); // 存入数据 studentScore.put("张三", 90); studentScore.put("李四", 85); // 读取数据 System.out.println("张三的分数:" + studentScore.get("张三")); System.out.println("缓存大小:" + studentScore.size()); // 判断是否存在 System.out.println("是否包含李四:" + studentScore.containsKey("李四")); // 移除数据 studentScore.remove("李四"); System.out.println("移除后缓存大小:" + studentScore.size()); } }