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.

83 lines
2.2 KiB

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class Cache<K, V> {
private final int capacity;
private final Map<K, V> cache;
public Cache(int capacity) {
this.capacity = capacity;
this.cache = new HashMap<>();
}
public void put(K key, V value) {
if (key == null) {
return;
}
if (cache.size() >= capacity && !cache.containsKey(key)) {
K oldestKey = cache.keySet().iterator().next();
cache.remove(oldestKey);
}
cache.put(key, value);
}
public V get(K key) {
return cache.get(key);
}
public void remove(K key) {
cache.remove(key);
}
public void clear() {
cache.clear();
}
public int getCapacity() {
return capacity;
}
public int getSize() {
return cache.size();
}
public boolean containsKey(K key) {
return cache.containsKey(key);
}
@SuppressWarnings("unchecked")
public Class<K> getKeyType() {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) type;
Type[] typeArgs = paramType.getActualTypeArguments();
if (typeArgs != null && typeArgs.length > 0 && typeArgs[0] instanceof Class) {
return (Class<K>) typeArgs[0];
}
}
return null;
}
@SuppressWarnings("unchecked")
public Class<V> getValueType() {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) type;
Type[] typeArgs = paramType.getActualTypeArguments();
if (typeArgs != null && typeArgs.length > 1 && typeArgs[1] instanceof Class) {
return (Class<V>) typeArgs[1];
}
}
return null;
}
@Override
public String toString() {
return "Cache{" +
"capacity=" + capacity +
", cache=" + cache +
'}';
}
}