LinkedHashMap framework for LRU cache

I am a little confused about how to create LRU cache using LinkedHashMap ( How to implement LRU cache in Java 6? ), And I want to make sure that I understand how it works inside behind the scenes.

Suppose I define a LRUMap class that extends LinkedHashMap and redefines removeEldestEntry(final Map.Entry<A, B> eldest)it the same way it does.

Then I create a data structure and insert 4 elements into the map

    LRUMap<String,String> map = new LRUMap<String,String>(3); //capacity 3
    map.put("a", "a");
    map.put("b", "b");
    map.put("c", "c");
    map.put("d", "d");

and interally LinkedHashMapuses Entry object, called headeras the starting node, to link all the elements you add to the map. So in this case it will be

   [header] ->  ["a"] -> ["b"] -> ["c"] -> ["d"] -> [header]

The header record object is both the beginning and the end of a doubly linked list, because header.before = header.after = header when it is initially constructed.

, (3 ), ,

    Entry<K,V> eldest = header.after;
    if (removeEldestEntry(eldest)) {
         removeEntryForKey(eldest.key);
    }
    .....

, [ "a" ]?
get(Object key), , (, "b" ) node,

     [header] ->  ["c"] -> ["d"] -> ["b"] -> [header]

.

+5
1
  • ; <"a", "a">: -)
  • , LinkedHashMap , ... :

    - Map . HashMap , , . , , ( ).

    LinkedHashMap ;

    constructor -, , , (-). LRU. put get ( ).

    , , get("b"); ( LRU ;-), .

?: -)

+10

All Articles