LRUCache是Least Recently Used 近期最少使用算法的缓存,是android提供的一个缓存工具类。可以以两种排序方式来输出缓存,一种是按插入顺序输出,一种是按最近最少方式输出,最近使用的放在队首,使用频率低的,间隔时间最长的放在队尾。
下面是实现

using System;
using System.Collections.Generic;
namespace LY.Helper
{
public class LRUCache<T>
{
private Dictionary<string, T> dict;
private LinkedList<T> list;
private int size = ;
private bool isSequence = false; public LRUCache(int sz):this(sz,false)
{ } public LRUCache(int sz, bool isSq)
{
isSequence = isSq;
size = sz < ? : sz;
dict = new Dictionary<string, T>(size);
list = new LinkedList<T>();
} public int Size
{
get { return size; }
set { size = value < ? : value; }
} public void Put(string key, T item)
{
T node;
if(dict.TryGetValue(key, out node))
{
list.Remove(node); dict[key] = item;
list.AddFirst(item);
}
else
{
if(list.Count == size)
list.RemoveLast();
dict[key] = item;
list.AddFirst(item);
}
} public T Get(string key)
{
T node;
if(dict.TryGetValue(key, out node))
{
list.Remove(node);
list.AddFirst(node);
return node;
}
return default(T);
} public ICollection<T> Values
{
get
{
if (isSequence)
{
return dict.Values;
}
else
{
return list;
}
}
}
}
}

构造函数中传入缓存大小和输出缓存顺序。
我们在调用Put方法时,当缓存长度超过我们构造函数中传入的大小时,会将队尾的移除。将新传入的对象放在队首。
我们从LRUCache中获取对象时,在Get方法中,会将对象移除,并置于队首。
下面我们来进行测试

private void btnTest_Click(object sender, EventArgs e)
{
LRUCache<int> lruCache = new LRUCache<int>();
lruCache.Put("", );
lruCache.Put("", );
lruCache.Put("", );
lruCache.Put("", );
lruCache.Put("", );
lruCache.Get("");
lruCache.Get(""); Console.WriteLine("最近最少方式Test...");
foreach (var item in lruCache.Values)
{
Console.WriteLine(item.ToString());
} LRUCache<int> lruCache1 = new LRUCache<int>(, true);
lruCache1.Put("", );
lruCache1.Put("", );
lruCache1.Put("", );
lruCache1.Put("", );
lruCache1.Put("", ); lruCache1.Get("");
lruCache1.Get(""); Console.WriteLine("顺序方式Test...");
foreach (var item in lruCache1.Values)
{
Console.WriteLine(item.ToString());
}
}

我们来看下输出结果

 

最新文章

  1. 使用Python中PIL图形库进行截屏
  2. python中zipfile文件名编码的问题
  3. Xamarin.Android中使用ResideMenu实现侧滑菜单
  4. springMVC配置步骤
  5. 浅谈压缩感知(二十六):压缩感知重构算法之分段弱正交匹配追踪(SWOMP)
  6. JAVA 接口与继承作业——动手动脑以及课后实验性问题
  7. c# 面相对象2-之封装性
  8. Stack的实现
  9. C#路径,文件,目录,I/O常见操作
  10. VS2013 Qt5 Mysql中文编码问题
  11. 搭建eureka服务
  12. PHP防止SQL注入和XSS攻击
  13. linux视频录制,推流处理
  14. centos7 安装部署zabbix
  15. 使用git clone命令克隆github项目到本地时出错,提示没有权限的解决方法
  16. HDU 2511 汉诺塔X
  17. 基于Swift语言开发微信、QQ和微博的SSO授权登录代码分析
  18. Linux应急响应(二):捕捉短连接
  19. 教程-TObjectList.Clear、TStringList.Clear方法对象有没有被释放
  20. python之微信公众号开发(基本配置和校验)

热门文章

  1. django2.0数据展示流程
  2. ES6系列_12之map数据结构
  3. echarts x轴文字显示不全(解决方案)
  4. js解决弹窗问题实现班级跳转DIV示例
  5. 串口通信,帧与帧之间的时间间隔问题?9600波特率,帧将各在20ms以上
  6. leetcode190
  7. ajax基本常识及get请求方式
  8. Python运维开发基础09-函数基础
  9. ios开发者账号、证书相关内容
  10. Spring IoC底层原理