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