-->

LinkedHashSet to implement LRU

2019-02-17 00:19发布

问题:

I want to remove the oldest member of a LinkedHashSet , I know that there's a removeEldestEntry method that I have to override (Java doc for removeEldestEntry ), but I guess that I have to define initial capacity and load factor which I don't care and I simply want to remove the element which was least recently accessed (here by access I mean being put while it's already in the set or being read)

Is there any way not to override removeEldestEntry ?

回答1:

I know that there's a removeEldestEntry method that I have to override

This statement is wrong since LinkedHashSet HAS-A LinkedHashMap and not IS-A.

You could use the useful (although not well known), Collections.newSetFromMap method:

Set<String> mySet = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>(){
    protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
        return size() > MAX_ENTRIES;
    }
});

It will thus return a Set vision of a LinkedHashMap (a Set-Like interface) implementing your custom removeEldestEntry method.

MAX_ENTRIES being a custom constant that you would have defined.



标签: java hashmap lru