As you can see from the code its very simple. All you have to do is extend
java.util.LinkedHashMapand override its protected
removeEldestEntry()method so that it checks if the size of map is greater than a size you specified while creating the Map if yes remove the eldest entry
Now the question is when Map is full which entry will it remove, you have 2 options
- Eldest: If you just want to remove the first entry that you inserted in the Map when adding a new entry then in your constructor you could use
super(cacheSize, 0.75f);, so LinkedHashMap wont keep track of when a particular entry were accessed.
- Least recently used (LRU): But if you want to make sure that the entry that was least recently used should be removed then call
super(cacheSize, 0.75f, true);from constructor of your LRUCache so that LinkedHashMap keeps track of when entry was accessed and removes the Least recently used entry