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();
        }
    }
}

 

posted @ 2020-07-15 18:06  使用D  阅读(262)  评论(0编辑  收藏  举报