一个最简单的LRUCache实现 (JAVA)

流程图:

 

 1. 代码

 1 import java.util.ArrayList;
 2 
 3 public class LRUCache {
 4     private int cacheMaxSize = 0;
 5     private ArrayList<Integer> pages = null; // Interger means page id
 6 
 7     public LRUCache(int cacheMaxSize) {
 8         this.cacheMaxSize = cacheMaxSize;
 9         pages = new ArrayList<Integer>();
10     }
11 
12     public void add(Integer p) {
13         if (pages.contains(p)) {
14             pages.remove(p);
15             pages.add(p);
16         } else if (pages.size() == cacheMaxSize) {
17             pages.remove(0);
18             pages.add(p);
19         } else {
20             pages.add(p);
21         }22     }
23 }

 2. 测试的代码

import java.util.ArrayList;
import java.util.Scanner;

import xqy.been.LRUCache;

public class LRU {
    private Scanner sc;
    private LRUCache lc = null;
    private ArrayList<Integer> pages = null;
    
    public LRU() {
        sc = new Scanner(System.in);
        pages = new ArrayList<Integer>();
        
        init();
        op();
    }
    
    private void init() {
        int key = -2;
        
        System.out.print("<LRU> 请输入物理块个数:");
        lc = new LRUCache(sc.nextInt());

        System.out.println("<LRU> 请按顺序输入页号(exit: -1): ");
        while (key != -1) {
            key = sc.nextInt();
            
            if (key > 0) {
                pages.add(key);
            }
        }
    }
    
    private void op() {
        for (int i = 0; i < pages.size(); i++) {
            lc.add(pages.get(i));
        }
    }
    
    public static void main(String[] args) {
        new LRU();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值