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.

103 lines
2.8 KiB

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Cache<K, V> {
// 使用HashMap作为底层存储
private Map<K, V> cacheMap;
// 缓存最大容量(可选)
private int maxCapacity;
public Cache() {
this.cacheMap = new HashMap<>();
this.maxCapacity = Integer.MAX_VALUE;
}
public Cache(int maxCapacity) {
this.cacheMap = new HashMap<>();
this.maxCapacity = maxCapacity;
}
// 添加缓存项
public void put(K key, V value) {
// 如果达到最大容量,可以实现淘汰策略(这里简单处理)
if (cacheMap.size() >= maxCapacity && maxCapacity > 0) {
// 简单策略:移除第一个元素
K firstKey = cacheMap.keySet().iterator().next();
cacheMap.remove(firstKey);
System.out.println("缓存已满,移除了key: " + firstKey);
}
cacheMap.put(key, value);
}
// 获取缓存项
public V get(K key) {
return cacheMap.get(key);
}
// 删除缓存项
public V remove(K key) {
return cacheMap.remove(key);
}
// 检查缓存项是否存在
public boolean containsKey(K key) {
return cacheMap.containsKey(key);
}
// 获取缓存大小
public int size() {
return cacheMap.size();
}
// 清空缓存
public void clear() {
cacheMap.clear();
}
// 获取所有key的集合
public Set<K> keySet() {
return cacheMap.keySet();
}
@Override
public String toString() {
return "Cache{" +
"size=" + cacheMap.size() +
", maxCapacity=" + maxCapacity +
", entries=" + cacheMap +
'}';
}
// 测试方法
public static void main(String[] args) {
// 创建缓存实例
Cache<String, Integer> cache = new Cache<>(3);
// 添加缓存项
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);
System.out.println("添加三个元素后: " + cache);
// 获取缓存项
System.out.println("获取key='b': " + cache.get("b"));
// 添加第四个元素(触发淘汰)
cache.put("d", 4);
System.out.println("添加第四个元素后: " + cache);
// 检查缓存项是否存在
System.out.println("key='a'是否存在: " + cache.containsKey("a"));
System.out.println("key='d'是否存在: " + cache.containsKey("d"));
// 删除缓存项
cache.remove("c");
System.out.println("删除key='c'后: " + cache);
// 清空缓存
cache.clear();
System.out.println("清空缓存后: " + cache);
}
}