首页 > 代码库 > Java LRU的实现

Java LRU的实现

最近在leetcode上做题的时,看到了一道有关LRU Cache的题目,正好我当初面试阿里巴巴的时候问到的。主要采用linkedHashMap来实现。

 

package edu.test.algorithm;import java.util.LinkedHashMap;public class LRUCache {    LinkedHashMap<Integer,Integer> linkedHashMap;    int capacity;    public LRUCache(int capacity) {        linkedHashMap=new LinkedHashMap<Integer, Integer>(capacity);        this.capacity=capacity;    }        public int get(int key) {            if(linkedHashMap.containsKey(key)){                int value=http://www.mamicode.com/linkedHashMap.get(key);                linkedHashMap.remove(key);                linkedHashMap.put(key, value);                return value;            }            return -1;            }        public void set(int key, int value) {              if(linkedHashMap.containsKey(key)){                     linkedHashMap.remove(key);                 }                 else if(linkedHashMap.size()>=capacity){                                               linkedHashMap.remove(linkedHashMap.keySet().iterator().next());                  }                  linkedHashMap.put(key, value);           }   }

 

Java LRU的实现