⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lrutest.txt

📁 用java实现操作系统中的lru算法
💻 TXT
字号:
/*  
 *Created on 2008-7-24  
 */  
import java.io.Serializable;   
import java.util.HashMap;   
import java.util.Iterator;   
import java.util.Vector;   
  
/**  
 * @author anwx<a href="mailto:luckyanzi@china.com.cn">An Weixiao</a>  
 * @version $Id$  
 */  
public class LRUTest {   
    protected HashMap<Object, Serializable> cache;   
    protected Vector<Object> cacheList;   
    protected int capacity = 3;   
       
    private int getCapacity(){   
        return this.capacity;   
    }   
       
    private int getSize(){   
        return cache.size();   
    }   
    public LRUTest(){   
        this.cache = new HashMap<Object, Serializable>();   
        this.cacheList = new Vector<Object>();   
    }   
    private void moveToTop(Object identifier) {   
        cacheList.insertElementAt(identifier,0);   
        if ( getSize() >= getCapacity() ) {   
            String toBeDeleted = (String)cacheList.lastElement();   
            cache.remove(toBeDeleted);   
            int lastElement = cacheList.size();   
            cacheList.remove(lastElement-1);   
        }   
    }   
    public Object get(Object identifier) {   
        if ( cache.containsKey(identifier) ) {   
            moveToTop(identifier);   
            Serializable co = (Serializable)cache.get(identifier);   
            return co;   
        }   
        else {   
            return null;   
        }   
    }   
       
    public void put(Object identifier, Serializable value) {    
        if (  getSize() < getCapacity() ) {               
            if ( !cache.containsKey(identifier) ) {                
                cacheList.insertElementAt(identifier,0);   
            }               
            cache.put(identifier,value);   
        }   
        else {   
            cache.put(identifier,value);   
            moveToTop(identifier);   
        }   
    }   
    private void print(){   
        System.out.println("data, key in cache");   
        Object key = null;   
        Serializable value = null;   
        for(Iterator it = cache.keySet().iterator(); it.hasNext();){   
            key = it.next();   
            System.out.println(String.format("[%s, %s]", cache.get(key), key));   
        }   
        System.out.println("key info sequence");   
        for(Object o: cacheList){   
            System.out.println(o);   
        }   
    }   
    public static void main(String args[]){   
        LRUTest test = new LRUTest();   
        test.put("1", "a");   
        test.put("2", "b");   
        test.put("3", "c");   
        test.print();   
        test.put("4", "d");   
        test.put("5", "e");   
        test.print();   
    }   
}  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -