1. 程式人生 > 實用技巧 >LRU資料結構-自定義

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