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.

31 lines
957 B

import java.util.HashMap;
import java.util.Map;
public class Cache<K, V> {
// 使用 HashMap 作为底层存储容器
private Map<K, V> storage = new HashMap<>();
public void put(K key, V value) {
storage.put(key, value);
}
public V get(K key) {
return storage.get(key);
}
public void remove(K key) {
storage.remove(key);
}
public boolean containsKey(K key) {
return storage.containsKey(key);
}
public int size() {
return storage.size();
}
public static void main(String[] args) {
Cache<String, String> userCache = new Cache<>();
userCache.put("user:1001", "Alice");
userCache.put("user:1002", "Bob");
String user1 = userCache.get("user:1001");
System.out.println("获取到的用户: " + user1);
if (userCache.containsKey("user:1002")) {
System.out.println("用户 1002 在缓存中");
}
}
}