A LRU Cache in 10 Lines of Java

I had a couple of interviews long ago which asked me to implemented a least recently used (LRU) cache. A cache itself can simply be implemented using a hash table, however adding a size limit gives an interesting twist on the question. Let’s take a look at how we can do this.

Least Recently Used Cache Eviction

To accomplish cache eviction we need to be easily able to:

  • query the last recently used item
  • mark an item as the most recently used item

A linked list allows for both operations. Checking for the least recently used item can just return the tail. Marking an item as recently used can be simply removing it from its current position and moving it to the head. The missing puzzle piece is finding this item in the linked list quickly.

Hash tables to the rescue

Looking into our data structure toolbox, hash tables allow us to easily index an object in (amortized) constant time. If we create a hash table from key -> list node, we can find the most recently used node in constant time. The converse is true in that we can also still check for the existence (or lack-there-of) in constant time as well.

After looking up the node we can then move it to the front of the linked list to mark it as the most recently used item.

The Java shortcut

Sometimes knowing less common data structures from the standard library of various programming languages can prove to be of help. Given this hybrid data structure we would have to implement a hash table on top of a linked list. However Java already provides this for us in the form of a LinkedHashMap! It even provides an overridable eviction policy method (removeEldestEntry docs). The only catch is that by default the linked list order is the insertion order, not access. However one of the constructor exposes an option use the access order instead (docs).

Without further ado:

import java.util.LinkedHashMap;
import java.util.Map;
 
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
  private int cacheSize;
 
  public LRUCache(int cacheSize) {
    super(16,  0.75f, true);
    this.cacheSize = cacheSize;
  }
 
  protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
    return size() >= cacheSize;
  }
}
时间: 2024-11-03 05:28:03

A LRU Cache in 10 Lines of Java的相关文章

LeetCode 之 LRU Cache Java实现

LeetCode刷了41道题了,流程是按照戴兄的小书,很多不会的是参考Kim姐的代码,自己用Java抠腚的. 前几天做到了LRU Cache: C++的实现方法大同小异,大都用的是一个list加一个hash,hash中存储list节点地址,每次get从hash中寻key,有则将list相应节点放到链表头,没有则返回-1:每次set先判断hash中是否存在,存在则将相应节点移到表头,重置value值,如果不存在,判定长度是否达到预设的capacity,如果达到,删除表尾节点,新节点插入表头. 但是

LRU Cache leetcode java

题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

Java for LeetCode 146 LRU Cache 【HARD】

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. set

[Leetcode][JAVA] LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(

LeetCode – LRU Cache (Java)

Problem Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return

lru cache java

http://www.acmerblog.com/leetcode-lru-cache-lru-5745.html acm之家的讲解是在是好,丰富 import java.util.LinkedHashMap; public class LRUCache { private int capacity; private LinkedHashMap<Integer,Integer> map=null; public LRUCache(int capacity) { this.capacity=ca

LRU (Least Recently Used) 算法的Java实现

实现代码如下: import java.util.LinkedHashMap; import java.util.Map; /**  * LRU (Least Recently Used) 算法的Java实现  * @param <K>  * @param <V>  * @author 杨尚川  */ public class LRUCache<K, V> extends LinkedHashMap<K, V> {     //缓存大小     privat

LeetCode——LRU Cache

Description: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise r

LRU算法 - LRU Cache

这个是比较经典的LRU(Least recently used,最近最少使用)算法,算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”. 一般应用在缓存替换策略中.其中的”使用”包括访问get和更新set. LRU算法 LRU是Least Recently Used 近期最少使用算法.内存管理的一种页面置换算法,对于在内存中但又不用的数据快(内存块)叫做LRU,Oracle会根据那些数据属于LRU而将其移出内存而腾出空间来加载另外的数据,一