posted 13 years ago
Hi Vinney,
in LRU cache the least recently used element in the cache is dropped when you add a new element, if you exceed the cache size.
You can customize a LinkedHashMap to behave exactly in that way.
1) You use a Map to store key,value pairs where the key is the cache address and value is the corresponding cache content.
2) In a LinkedHashMap you have a method called removeEldestEntry (see API documentation) that returns true if the eldest element in the linked map has to be deleted. (and in LRU it has to when you exceed the cache size)
3) LinkedHashMap has a constructor in which you can specify the ordering mode
in the above constructor if the parameter accessOrder is set to true, the last accessed entry (i.e. the last one you retrieve with method get) becomes the first in list, the newest one, the most recently used.
Now i suggest you to write a simple example in which you build a LinkedHashMap of,for instance, 5 elements (where five is the cache size) and to override removeEldestEntry method in such a way that you remove the eldest entry (last accessed one) when you try to insert the sixth element.