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

后端 未结 14 1701
刺人心
刺人心 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 07:42

    public class LeastRecentlyUsed {
    
        public static  Map leastRecentlyUsedCache(final int maxSize) {
            return new LinkedHashMap(maxSize , 0.7f, true) {
                private static final long serialVersionUID = -3588047435434569014L;
                @Override
                protected boolean removeEldestEntry(Map.Entry eldest) {
                    return size() > maxSize;
                }
            };
        }
    
        public static void main(String[] args) {
            Map leastRecentlyUsed = LeastRecentlyUsed.leastRecentlyUsedCache(3);
            leastRecentlyUsed.put("Robert", "Raj");
            leastRecentlyUsed.put("Auzi", "Aiz");
            leastRecentlyUsed.put("Sandy", "S");
            leastRecentlyUsed.put("Tript", "tty");  
            System.out.println(leastRecentlyUsed);
        }
      }
    

提交回复
热议问题