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.
51 lines
1.2 KiB
51 lines
1.2 KiB
package w8;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
public class Cache<K, V> {
|
|
private final Map<K, V> cache = new HashMap<>();
|
|
|
|
// 存入缓存
|
|
public void put(K key, V value) {
|
|
cache.put(key, value);
|
|
}
|
|
|
|
// 从缓存获取
|
|
public V get(K key) {
|
|
return cache.get(key);
|
|
}
|
|
|
|
// 移除缓存
|
|
public V remove(K key) {
|
|
return cache.remove(key);
|
|
}
|
|
|
|
// 清空缓存
|
|
public void clear() {
|
|
cache.clear();
|
|
}
|
|
|
|
// 判断是否包含key
|
|
public boolean containsKey(K key) {
|
|
return cache.containsKey(key);
|
|
}
|
|
|
|
// 获取缓存大小
|
|
public int size() {
|
|
return cache.size();
|
|
}
|
|
|
|
// 测试
|
|
public static void main(String[] args) {
|
|
Cache<String, Integer> studentScore = new Cache<>();
|
|
studentScore.put("张三", 90);
|
|
studentScore.put("李四", 85);
|
|
|
|
System.out.println("张三的分数:" + studentScore.get("张三"));
|
|
System.out.println("缓存大小:" + studentScore.size());
|
|
|
|
studentScore.remove("李四");
|
|
System.out.println("移除李四后,缓存是否包含李四?" + studentScore.containsKey("李四"));
|
|
}
|
|
}
|