You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.3 KiB

import java.util.HashMap;
import java.util.Map;
public class Cache<K, V> {
// 用Map存储缓存数据
private final Map<K, V> 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<String, Integer> 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());
}
}