Skip to content

Instantly share code, notes, and snippets.

@showsky
Created June 12, 2014 10:28
Show Gist options
  • Select an option

  • Save showsky/d0650adc609801096db1 to your computer and use it in GitHub Desktop.

Select an option

Save showsky/d0650adc609801096db1 to your computer and use it in GitHub Desktop.
Java) Least Recently Used use LinkedHashMap
public class LRUHashMap<K, V> extends LinkedHashMap<K, V> {
private int limit = 0;
public LRUHashMap(int limit) {
super(limit, 0.75f, true);
this.limit = limit;
}
@Override
protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
return size() > limit;
}
}
import java.util.Map.Entry;
public class Main {
private final static int size = 3;
public static void main(String[] args) {
LRUHashMap<String, Integer> lru = new LRUHashMap<String, Integer>(size);
lru.put("a", 1);
lru.put("b", 1);
lru.put("c", 1);
// print a, b, c
print(lru);
// use
lru.get("a");
lru.put("d", 1);
// print c, a, d
print(lru);
}
public static void print(LRUHashMap<String, Integer> lru) {
for (Entry<String, Integer> entry: lru.entrySet()) {
System.out.println(entry.getKey());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment