import java.util.HashMap; import java.util.Map; public class Cache { // 底层用 HashMap 存储数据 private final Map cacheMap; public Cache() { this.cacheMap = new HashMap<>(); } // 存入缓存 public void put(K key, V value) { cacheMap.put(key, value); } // 从缓存获取 public V get(K key) { return cacheMap.get(key); } // 删除缓存 public void remove(K key) { cacheMap.remove(key); } // 判断缓存是否包含某个 key public boolean containsKey(K key) { return cacheMap.containsKey(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); studentScoreCache.put("王五", 95); // 查询数据 System.out.println("张三的分数:" + studentScoreCache.get("张三")); System.out.println("缓存大小:" + studentScoreCache.size()); // 删除数据 studentScoreCache.remove("李四"); System.out.println("删除李四后缓存大小:" + studentScoreCache.size()); System.out.println("是否包含李四?" + studentScoreCache.containsKey("李四")); // 清空缓存 studentScoreCache.clear(); System.out.println("清空后缓存大小:" + studentScoreCache.size()); } }