Java solution using LinkedHashMap


  • 10
    N
    import java.util.*;
    
    public class LRUCache {
        LinkedHashMap<Integer, Integer> cache;
        public LRUCache(int capacity) {
          cache = new LinkedHashMap<Integer, Integer>(){
          
          @Override
          protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
            if(cache.size() > capacity) {
              return true;
            }
            return false;
          }
        };
       }
        
        public int get(int key) {
          if(cache.containsKey(key)) {
            int value = cache.get(key);
            moveToFront(key);
            return value;
          }
          return -1;
        }
        
        void moveToFront(int key) {
     
          int val = cache.get(key);
          cache.remove(key);
          cache.put(key,val);
        }
        
        public void set(int key, int value) { 
          cache.put(key, value);
          moveToFront(key);
        }
    }

  • 0
    J

    why removeEldestEntry need to be overridden? it's defined as this:

       removeEldestEntry(Map.Entry<K,V> eldest)
    

    Returns true if this map should remove its eldest entry. Does this mean each time I declare a LinkedHashMap this method need to be overridden? Thanks for answering.


  • 1
    B

    You have to override it in order to specify that you want to remove the eldest entry once you've hit the max capacity defined by the constructor.
    If you do not override, this method will always return false by default, as defined in the the Java source code.


  • 0
    M

    Is there a way I can call removeEldestEntry and save the eldest entry to DataBase?


  • 0
    L

    @manzoor you can use cache.keySet(), it is in the order you want!


  • 0
    L

    This is vary nice solution in Java, space and time!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.