用linkList实现LRU算法

写于: 2011-10-30 11:59, 自己的博客转移。

http://www.blogjava.net/lsbwahaha/archive/2010/08/15/328918.html


public class LRUCache<K,V> {

    final private int capacity;
    final private Map<K,Reference<V>> map;
    final private ReentrantLock lock = new ReentrantLock();
    final private ReferenceQueue<Reference<V>> queue = new ReferenceQueue<Reference<V>>();
   
    public LRUCache(int capacity) {
 this.capacity = capacity;
 map = new LinkedHashMap<K,Reference<V>>(capacity,1f,true){
     @Override
     protected boolean removeEldestEntry(Map.Entry<K,Reference<V>> eldest) {
         return this.size() > LRUCache.this.capacity;
     }
 };
    }
   
    public V put(K key,V value) {
 lock.lock();
 try {
  map.put(key, new SoftReference(value,queue));
  return value;
 }finally {
     lock.unlock();
 }
    }
   
    public V get(K key) {
 lock.lock();
 try {
     queue.poll();
     return map.get(key).get();
 }finally {
     lock.unlock();
 }
    }
 
    public void remove(K key) {
 lock.lock();
 try {
     map.remove(key);
 }finally {
     lock.unlock();
 }
    }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * 基于向量实现的完全二叉树 */ package dsa; public class ComplBinTree_Vector extends BinTree_LinkedList implements ComplBinTree { private Vector T;//向量 //构造方法:默认的空树 public ComplBinTree_Vector() { T = new Vector_ExtArray(); root = null; } //构造方法:按照给定的节点序列,批量式建立完全二叉树 public ComplBinTree_Vector(Sequence s) { this(); if (null !=s) while (!s.isEmpty()) addLast(s.removeFirst()); } /*---------- BinaryTree接口中各方法的实现 ----------*/ //返回树根(重写) public BinTreePosition getRoot() { return T.isEmpty() ? null : posOfNode(0); } //判断是否树空(重写) public boolean isEmpty() { return T.isEmpty(); } //返回树的规模(重写) public int getSize() { return T.getSize(); } //返回树(根)的高度(重写) public int getHeight() {return isEmpty() ? -1 : getRoot().getHeight(); } /*---------- ComplBinTree接口中各方法的实现 ----------*/ //生成并返回一个存放e的外部节点,该节点成为新的末节点 public BinTreePosition addLast(Object e) { BinTreePosition node = new ComplBinTreeNode_Rank(T, e); root = (BinTreePosition) T.getAtRank(0); return node; } //删除末节点,并返回其中存放的内容 public Object delLast() { if (isEmpty()) return null;//若树(堆)已空,无法删除 if (1 == getSize()) root = null;//若删除最后一个节点,则树空 return T.removeAtRank(T.getSize()-1); } //返回按照层次遍历编号为i的节点的位置,0 <= i < size() public BinTreePosition posOfNode(int i) { return (BinTreePosition)T.getAtRank(i); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值