1 changed files with 45 additions and 0 deletions
@ -0,0 +1,45 @@ |
|||
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
|
|||
} |
|||
} |
|||
Loading…
Reference in new issue