Timur Timur - 3 months ago 31
Java Question

RemoveEldestEntry in LinkedHashmap while trying to implement LRU algorithm in java

I have this code and I want to understand how it works.

public class LRUAlgoCacheImpl<K,V> implements IAlgoCache<K,V>{

private int capacity;

private LinkedHashMap<K,V> lhm;
public LRUAlgoCacheImpl(int capacity) {
lhm = new LinkedHashMap<K,V>(capacity+1,1.1f, true) {
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return lhm.size()> capacity;
}
};
this.capacity=capacity;
}


I understand that it overrides the
removeEldestEntry
in the
LinkedHashMap
class,but i don't quite understand how.
I could extend
LinkedHashmap
in my class declaration without doing so and just doing regular override, but I'm trying to learn more.
Could someone explain this to me please?
Thank you in advance.

Answer

The class LRUAlgoCacheImpl implements a LRU (Least Recently Used) algorithm by applying the OO design concept of composition with an anonymous inner class that extends a LinkedHashMap in order to override removeEldestEntry(Map.Entry) to be able to evict the oldest entry when the size of the map exceeds the provided capacity.

Why applying Composition over Inheritance?

The main reason is related to the fact that in Java you can extend only one class unlike C++ for example so if you choose class Inheritance you could face design issues later if you need to make your code evolve. On the other side Composition makes you implement interfaces which is a good design practice and as you can implement as many interfaces as you want, the Composition approach is much more flexible and so a better choice for maintainability.