• Java实现一个简单的LRUCache


    流程图:

     

     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();
        }
    }
  • 相关阅读:
    在linux上安装python, jupyter, 虚拟环境(virtualenv)以及 虚拟环境管理之virtualenvwraper
    linux
    Django ORM那些相关操作
    Django 中 form 介绍
    MySQL完整性约束
    git入门
    MySQL表的操作
    努力努力再努力
    Docker初始
    IO模型
  • 原文地址:https://www.cnblogs.com/daheww/p/10192376.html
Copyright © 2020-2023  润新知