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.
65 lines
1.6 KiB
65 lines
1.6 KiB
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
public class Cache<K, V> {
|
|
private Map<K, V> cacheMap;
|
|
private int maxSize;
|
|
|
|
public Cache() {
|
|
this.cacheMap = new HashMap<>();
|
|
this.maxSize = Integer.MAX_VALUE;
|
|
}
|
|
|
|
public Cache(int maxSize) {
|
|
this.cacheMap = new HashMap<>();
|
|
this.maxSize = maxSize;
|
|
}
|
|
|
|
public void put(K key, V value) {
|
|
if (cacheMap.size() >= maxSize) {
|
|
K firstKey = cacheMap.keySet().iterator().next();
|
|
cacheMap.remove(firstKey);
|
|
}
|
|
cacheMap.put(key, value);
|
|
}
|
|
|
|
public V get(K key) {
|
|
return cacheMap.get(key);
|
|
}
|
|
|
|
public boolean containsKey(K key) {
|
|
return cacheMap.containsKey(key);
|
|
}
|
|
|
|
public V remove(K key) {
|
|
return cacheMap.remove(key);
|
|
}
|
|
|
|
public int size() {
|
|
return cacheMap.size();
|
|
}
|
|
|
|
public void clear() {
|
|
cacheMap.clear();
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return cacheMap.toString();
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
Cache<String, Integer> cache = new Cache<>(3);
|
|
cache.put("A", 1);
|
|
cache.put("B", 2);
|
|
cache.put("C", 3);
|
|
System.out.println("Cache after adding A,B,C: " + cache);
|
|
|
|
cache.put("D", 4);
|
|
System.out.println("Cache after adding D (maxSize=3): " + cache);
|
|
|
|
System.out.println("Get B: " + cache.get("B"));
|
|
System.out.println("Contains C: " + cache.containsKey("C"));
|
|
System.out.println("Size: " + cache.size());
|
|
}
|
|
}
|