LRU: (least recently used) The least recent algorithm has been used. LRU algorithm in the Java data structure implementation is a LRU algorithm in the interview frequently asked questions, we can use LinkedList to express the latest and least use. The accessed data is stored in the LinkedList data structure, and if the search is minimal, return directly to the tail node of the LinkedList. If you add a recently accessed data A, you can remove a from the location in the list and move to the head of the list.
However, the location of the query data in the list is generally slow to access, so we need to use other data structure to complete the lookup, we know HashMap is an efficient query data structure. If we use this data as the key, and the corresponding node of HashMap is stored in the value, then we can get the operation of query complexity O (1).
Java has helped us implement a data structure that is consistent with the location of the key values stored in the Linkedhashmap.linkedhashmap. Will not change, you can set linkedhashmap in the order of insertion, or in the order of access, the first access is placed at the last, most recently accessed at the front.
The LINKEDHASHMAP itself has implemented sequential storage by default, stored in the order in which the elements are added, or enabled in the order of access, where the most recently read data is at the front, the oldest read is on the last side, and then it has a way of determining whether to delete the oldest data. The default is to return False, that is, do not delete the data, we use LINKEDHASHMAP implementation of LRU cache is a simple extension of linkedhashmap, the following is a simple implementation. Import Java.util.LinkedHashMap; Import Java.util.Map; Public lrucache<k, v> extends Linkedhashmap<k, v> {private int cacheSize; Cache value Size public LRUCache (int cacheSize) {super (0.75, true); The true setting is sorted by Access order this. cacheSize = CacheSize; } protected Boolean removeeldestentry (Map.entry<k, v> eldest) {return size () >= cacheSize; If the size of the linkedhashmap exceeds the cached value, return true to delete the oldest data}}