Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 30, 2019 23:42
Show Gist options
  • Save shixiaoyu/8ac8db365ccfa1aa1c197a187d8d1f15 to your computer and use it in GitHub Desktop.
Save shixiaoyu/8ac8db365ccfa1aa1c197a187d8d1f15 to your computer and use it in GitHub Desktop.
// I really don't like inheritance, i prefer composition, but the removeEldestEntry is a protected method, have to do this
public class LRULinkedHashMap extends LinkedHashMap<Integer, Integer> {
private int maxSize = -1;
// This is simply use a LinkedHashMap, sort of cheating
public LRULinkedHashMap(int capacity) {
super(16, 0.75f, true); // the 16 hashtable size is not to be confused with the max cache size
this.maxSize = capacity;
}
public int get(int key) {
return (int)super.getOrDefault(key, -1);
}
public void put(int key, int value) {
super.put(key, value);
}
// as suggested in the java doc
@Override
public boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return super.size() > this.maxSize;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment