import java.util.HashMap;
import java.util.Map;
public class SimpleCache<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 void remove(K key) {
cache.remove(key);
}
// 检查缓存中是否存在指定的键
public boolean containsKey(K key) {
return cache.containsKey(key);
}
// 清空缓存
public void clear() {
cache.clear();
}
public static void main(String[] args) {
SimpleCache<String, String> myCache = new SimpleCache<>();
// 添加缓存
myCache.put("key1", "value1");
myCache.put("key2", "value2");
// 获取缓存
System.out.println("Value for key1: " + myCache.get("key1")); // 输出: Value for key1: value1
// 检查缓存中是否存在键
System.out.println("Contains key3: " + myCache.containsKey("key3")); // 输出: Contains key3: false
// 移除缓存
myCache.remove("key1");
System.out.println("Contains key1 after removal: " + myCache.containsKey("key1")); // 输出: Contains key1 after removal: false
// 清空缓存
myCache.clear();
System.out.println("Cache size after clear: " + myCache.cache.size()); // 输出: Cache size after clear: 0
}
}
HashMap
来存储键值对。SimpleCache
类进行基本操作。上一篇:java datetime
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站