首页 > 其他分享 >LRUCache (least recently used)

LRUCache (least recently used)

时间:2023-08-25 16:47:54浏览次数:143  
标签:used recently Object least value key return keyList null

 

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Caching with the LRU (Least Recently Used) algorithm.
 * 
 */
public class LRUCache {

    private Map<Object, Object> cache = new HashMap<Object, Object>();

    private LinkedList<Object> keyList = new LinkedList<Object>();

    private int maxSize;

    public LRUCache(int maxSize) {
        if (maxSize < 1) {
            throw new IllegalArgumentException("LRUCache max size must be greater than 0");
        }
        this.maxSize = maxSize;
    }

    public synchronized void put(Object key, Object value) {
        if (key == null) {
            return;
        }
        keyList.remove(key);
        keyList.addFirst(key);
        cache.put(key, value);

        if (cache.size() > maxSize) {
            Object lastKey = keyList.getLast();
            this.remove(lastKey);
        }
    }

    public synchronized Object get(Object key) {
        if (key == null) {
            return null;
        }
        Object value = cache.get(key);
        if (value == null) {
            return null;
        }

        keyList.remove(key);
        keyList.addFirst(key);
        return value;
    }

    public synchronized Object remove(Object key) {
        if (key == null) {
            return null;
        }
        Object value = cache.remove(key);
        if (value == null) {
            return null;
        }
        keyList.remove(key);
        return value;
    }

    public synchronized void clear() {
        cache.clear();
        keyList.clear();
    }
}

 

备注

https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist

什么时候用LinkedList 

什么时候用ArrayList

什么时候用HashMap

什么时候用LinkedHashMap

 

标签:used,recently,Object,least,value,key,return,keyList,null
From: https://www.cnblogs.com/zno2/p/7010271.html

相关文章