LRU cache in Java with Generics and O(1) operations

后端 未结 14 1718
刺人心
刺人心 2020-12-02 07:12

This is a question that comes up a lot in job interviews. The idea is to define a data structure instead of using Java\'s built in LinkedHashMap.

An LRU cache delete

14条回答
  •  半阙折子戏
    2020-12-02 08:03

    Here is the java implementation with Generics and LinkedHashMap, and complexity of O(1) on get() and put().

    import java.util.LinkedHashMap;
    
    public class LRUCache {
    
        private LinkedHashMap lruCacheMap;
        private final int capacity;
        private final boolean SORT_BY_ACCESS = true;
        private final float LOAD_FACTOR = 0.75F;
    
        public LRUCache(int capacity){
            this.capacity = capacity;
            this.lruCacheMap = new LinkedHashMap<>(capacity, LOAD_FACTOR, SORT_BY_ACCESS);
        }
    
        public V get(K k){
            return lruCacheMap.get(k);
        }
    
        public void put(K k, V v){
            if(lruCacheMap.containsKey(k)){
                lruCacheMap.remove(k);
            }else if(lruCacheMap.size() >= capacity){
                lruCacheMap.remove(lruCacheMap.keySet().iterator().next());
            }
            lruCacheMap.put(k, v);
        }
    
        public void printSequence(){
            System.out.println(lruCacheMap.keySet());
        }
    }
    

    This is the code for testing it:

    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    public class TestLruCache {
    
        static class MyHardDrive {
            Map resources = new HashMap<>();
    
            MyHardDrive(){
                for(Character i='A'; i<='Z'; i++){
                    resources.put(i.toString(), new Object());
                }
            }
    
            Object loadResource(String name){
                return resources.get(name);
            }
        }
    
        public static void main(String[] args) {
            MyHardDrive hd = new MyHardDrive();
            LRUCache cache = new LRUCache<>(4);
    
            for(String key: Arrays.asList("A","B","C","A","D","E","F","E","F","G","A")){
                Object object = cache.get(key);
                if(object==null){
                    object = hd.loadResource(key);
                    cache.put(key, object);
                }
                cache.printSequence();
            }
        }
    }
    

提交回复
热议问题