zoukankan      html  css  js  c++  java
  • LRU数据结构-自定义

        public static void main(String[] args) {
            try {
                LRUStruct lruStruct = new LRUStruct(4);
                lruStruct.put("1", 1);
                lruStruct.put("2", 2);
                lruStruct.put("3", 3);
                lruStruct.put("4", 4);
                lruStruct.put("5", 5);
                System.out.println(lruStruct.toString());
                lruStruct.get("2");
    
                System.out.println(lruStruct.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        static class LRUStruct<T, W> {
            //存储key对应的list中位置,用于get时,把get的key放在最后
            private HashMap<T, Integer> existConfig = new HashMap();
            //存储实际数据
            private HashMap<T, W> data = new HashMap();
            //key位置
            private List<T> list;
            private int max;
    
            public LRUStruct(int count) throws Exception {
                if (count <= 0) {
                    throw new Exception("count必须大于0");
                }
                this.max = count;
                this.list = new ArrayList<>(max);
            }
    
            public void put(T key, W value) {
                if (!existConfig.containsKey(key)) {
                    this.existConfig.put(key, list.size());
                    this.list.add(key);
                    this.data.put(key, value);
                }
            }
    
            public W get(T key) {
                if (existConfig.containsKey(key)) {
                    int p = existConfig.get(key);
                    this.list.remove(p);
                    this.list.add(key);
                }
                return data.containsKey(key) ? data.get(key) : null;
            }
    
            public String toString() {
                StringBuffer stringBuffer = new StringBuffer();
                for (T key : list) {
                    stringBuffer.append("key=" + key).append(";value=" + data.get(key));
                }
                return stringBuffer.toString();
            }
        }
    }
  • 相关阅读:
    react-dnd例子代码学习记录
    GitKraken使用记录
    Table-dnd-tree代码分析
    umi-request请求码200,但是response是网页
    MyBatis-Plus配置输出日志
    PAT甲级1021解法
    PAT甲级1020解法
    PAT甲级1019解法
    PAT甲级1017解法
    PAT甲级1018解法
  • 原文地址:https://www.cnblogs.com/use-D/p/13307095.html
Copyright © 2011-2022 走看看