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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With