一个最简单的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();
    }
}
原文地址:https://www.cnblogs.com/shoshana-kong/p/14627838.html