Created
June 12, 2014 10:28
-
-
Save showsky/d0650adc609801096db1 to your computer and use it in GitHub Desktop.
Java) Least Recently Used use LinkedHashMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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