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

流程图:

 一个最简单的LRUCache实现 (JAVA)_第1张图片

 1. 代码

 1 import java.util.ArrayList;
 2 
 3 public class LRUCache {
 4     private int cacheMaxSize = 0;
 5     private ArrayList pages = null; // Interger means page id
 6 
 7     public LRUCache(int cacheMaxSize) {
 8         this.cacheMaxSize = cacheMaxSize;
 9         pages = new ArrayList();
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 pages = null;
    
    public LRU() {
        sc = new Scanner(System.in);
        pages = new ArrayList();
        
        init();
        op();
    }
    
    private void init() {
        int key = -2;
        
        System.out.print(" 请输入物理块个数:");
        lc = new LRUCache(sc.nextInt());

        System.out.println(" 请按顺序输入页号(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();
    }
}

 

你可能感兴趣的:(Java算法)