Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashSet to implement LRU

Tags:

java

hashmap

lru

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 ?

like image 415
Arian Avatar asked Jun 22 '13 21:06

Arian


1 Answers

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.

like image 155
Mik378 Avatar answered Sep 21 '22 13:09

Mik378