Skip to content

Instantly share code, notes, and snippets.

@kantenkugel
Last active May 6, 2024 12:17
Show Gist options
  • Save kantenkugel/32683eca6862345de299dd4b30421016 to your computer and use it in GitHub Desktop.
Save kantenkugel/32683eca6862345de299dd4b30421016 to your computer and use it in GitHub Desktop.
Java Cache with Map/List and maximum size
import java.util.HashMap;
import java.util.Map;
public class FixedSizeCache<K, V> {
private final Map<K, V> map = new HashMap<>();
private final K[] keys;
private int currIndex = 0;
public FixedSizeCache(int size) {
if(size < 1)
throw new IllegalArgumentException("Cache size must be at least 1!");
this.keys = (K[]) new Object[size];
}
public void add(K key, V value) {
if(!contains(key)) {
if(keys[currIndex] != null) {
map.remove(keys[currIndex]);
}
keys[currIndex] = key;
currIndex = (currIndex + 1) % keys.length;
}
map.put(key, value);
}
public boolean contains(K key) {
return map.containsKey(key);
}
public V get(K key) {
return map.get(key);
}
}
import java.util.Map;
import java.util.LinkedHashMap;
public class FixedSizeCacheNew<K, V> extends LinkedHashMap<K,V> {
private final int maxSize;
public FixedSizeCacheNew(int size) {
super(size+2, 1F); //+2 to have place for the newly added element AND not fill up to cause resize
this.maxSize = size;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size() > maxSize;
}
}
import java.util.LinkedList;
public class FixedSizeList<T> {
private final LinkedList<T> list = new LinkedList<>();
private final int maxSize;
public FixedSizeList(int size) {
if(size < 1)
throw new IllegalArgumentException("List size must be at least 1!");
this.maxSize = size;
}
public void add(T value) {
if(list.size() == maxSize) {
list.removeFirst();
}
list.add(value);
}
public boolean contains(T value) {
return list.contains(value);
}
public T getFirst() {
return list.getFirst();
}
public T get(int index) {
return list.get(index);
}
}
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import java.util.AbstractQueue;
public class FixedSizeQueue<E> extends AbstractQueue<E> implements Queue<E> {
private final Queue<E> queue;
private final int maxSize;
public FixedSizeQueue(int size) {
this.queue = new ArrayDeque<>(size);
this.maxSize = size;
}
@Override
public Iterator<E> iterator() {
return queue.iterator();
}
@Override
public int size() {
return queue.size();
}
@Override
public boolean offer(E e) {
if(size() >= maxSize)
queue.poll();
return queue.offer(e);
}
@Override
public E poll() {
return queue.poll();
}
@Override
public E peek() {
return queue.peek();
}
}
@darius-sas
Copy link

Thank you, very helpful and avoids me the hassle of writing one myself! :)

@hrieke
Copy link

hrieke commented May 6, 2024

Great work! Do you have a license for this code?
Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment