# 原地址
https://leetcode-cn.com/problems/lru-cache/
# 原理分析
- 重写LinkedHashMap中的removeEldestEntry方法,其中<font color='red'>capacity</font>为容器的总大小,<font color='red'>0.75</font>为扩容因子,<font color='red'>accessOrder</font>为true是开启顺序访问。
- 如果不用这个方法,就需要自己维护一个有序的HashMap。通过研究LinkedHashmap发现,它<font color='red'>重写</font>了hashmap中的<font color='red'>newNode</font>方法,当前Entry创建后,放入一个LinkNode中完成有序,这样我们在取数据的时候,只要通过linkNode就可以顺序拿出Entry,并且也能获取key和value。
```java
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p =
new LinkedHashMap.Entry<K,V>(hash, key, value, e);
linkNodeLast(p);
return p;
}
```
# 代码
```java
class LRUCache {
private LinkedHashMap<Integer, Integer> map;
public LRUCache(int capacity) {
map = new LinkedHashMap(capacity, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return map.size() > capacity;
}
};
}
public int get(int key) {
return map.getOrDefault(key, -1);
}
public void put(int key, int value) {
map.put(key, value);
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
```

146. LRU 缓存机制和LinkedHashMap底层研究