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.
45 lines
943 B
45 lines
943 B
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
public class Cache<K, V> {
|
|
private final Map<K, V> map = new HashMap<>();
|
|
|
|
// 存入缓存
|
|
public void put(K key, V value) {
|
|
map.put(key, value);
|
|
}
|
|
|
|
// 获取缓存
|
|
public V get(K key) {
|
|
return map.get(key);
|
|
}
|
|
|
|
// 删除缓存
|
|
public void remove(K key) {
|
|
map.remove(key);
|
|
}
|
|
|
|
// 清空缓存
|
|
public void clear() {
|
|
map.clear();
|
|
}
|
|
|
|
// 查看大小
|
|
public int size() {
|
|
return map.size();
|
|
}
|
|
|
|
// 是否包含某个key
|
|
public boolean containsKey(K key) {
|
|
return map.containsKey(key);
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
Cache<String, String> cache = new Cache<>();
|
|
cache.put("user1", "Alice");
|
|
cache.put("user2", "Bob");
|
|
|
|
System.out.println(cache.get("user1")); // Alice
|
|
System.out.println(cache.size()); // 2
|
|
}
|
|
}
|