LRU Cache

看了下RU(Least Recently Used ,最近最少使用),可以使用LinkedHashMap实现,到是蛮简单的.LinkedHashMap会将get或是put的数据置于底端.
重写removeEldestEntry()可以设定根据size来调整cache的数量.


import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* This class uses the LinkedHashMap to build LRU cache.
* User can define the cache size.
*/
public class LRUCache
{
int cacheSize = 0;
float loadFactor = 0.75f; //default
LinkedHashMap map;

public LRUCache(int cacheSize)
{
this.cacheSize = cacheSize;
map = new LinkedHashMap(cacheSize, loadFactor, true)
{
protected boolean removeEldestEntry(Map.Entry eldest)
{
return size() > LRUCache.this.cacheSize;
//return false;
}
};
}

public synchronized void clear()
{
map.clear();
}

public synchronized Object get(Object key)
{
return map.get(key);
}

public synchronized void put(Object key, Object value)
{
map.put(
key,
value);
}

public synchronized Object remove(Object key)
{
return map.remove(key);
}

public synchronized int size()
{
return map.size();
}

public synchronized Collection values()
{
return map.values();
}

public static void main(String []args)
{
// testing
int size = 3;
LRUCache cache = new LRUCache(size);
cache.put(new Integer("1"), "1");
cache.put(new Integer("2"), "2");
cache.put(new Integer("3"), "3");

String value = (String)cache.get(new Integer(1));
System.out.println(value);
System.out.println("Testing ...");

Object[] values = cache.values().toArray();
for (int i = 0; i < values.length; i++)
{
value = (String)values[i];
System.out.println(value);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值