LinkedHashSet for implementing LRU

I want to remove the oldest LinkedHashSet element, I know that there is a removeEldestEntry method that I have to override ( Java doc for removeEldestEntry ), but I assume that I need to determine the initial capacity and load factor , which I don't care, and I just want to remove the element that was last available (here by access I mean put , while it is already in the set or is being read)

Is it possible to override removeEldestEntry ?

+6
source share
1 answer

I know that there is a removeEldestEntry method that I have to override

This statement is not true because LinkedHashSet HAS-A is LinkedHashMap , not IS-A.

You can use the useful (albeit not very 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; } }); 

In this way, it will return the Set LinkedHashMap (Set-Like interface) view, implementing your own removeEldestEntry method.

MAX_ENTRIES is a custom constant that you would define.

+15
source

Source: https://habr.com/ru/post/947913/


All Articles