Skip to content

Instantly share code, notes, and snippets.

@benrhine
Created July 7, 2025 17:34
Show Gist options
  • Save benrhine/8d33d794d13ac53e8af6720b6a099e15 to your computer and use it in GitHub Desktop.
Save benrhine/8d33d794d13ac53e8af6720b6a099e15 to your computer and use it in GitHub Desktop.
LRUCache
class LRUCache {
private final int capacity;
private final LinkedHashMap<Integer, Integer> cache;
public LRUCache(int capacity) {
this.capacity = capacity;
this.cache = new LinkedHashMap<Integer, Integer>(capacity, 1, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
};
}
public int get(int key) {
return cache.getOrDefault(key, -1);
}
public void put(int key, int value) {
cache.put(key, value);
}
public int size() {
return this.cache.size();
}
public LinkedHashMap<Integer, Integer> getCache() {
return this.cache;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment