Design and implement a data structure for least recently used (LRU) cache. It shocould support the following operations:get
Andset
.
get(key)
-Get the value (will always be positive) of the key if the key exists in the cache, otherwise return-1.
set(key, value)
-Set or insert the value if the key is not already present. When the cache reached its capacity, it shocould invalidate the least recently used item before inserting a new item.
Linkedhashmap provides specialConstructor
To create a link hash ing. The iterative order of the hash ing is the order in which the entries are finally accessed, from the minimum recent access to the most recent access (Access Sequence). This type of ing is suitable for building LRU caches. CallPutOrGetThe method will access the corresponding entries (assuming it still exists after the call is complete ).PutallThe method is to generate an entry access for each ing of a specified ing based on the key-value ing relationship provided by the entry set iterator of the specified ing.No other methods generate entry access.In particular, the operations on the collection ViewNoThe iteration sequence that affects the underlying ing.
Rewrite allowedremoveEldestEntry(Map.Entry)
To automatically remove the old ing when adding the new ing to the ing.
This class provides all optionalMapOperation, and the null element is allowed. AndHashmapIt can be a basic operation (Add,ContainsAndRemove) Provides stable performance, assuming that the hash function correctly distributes elements to the bucket. Because the cost of maintaining the link list is increased, the performance is likely to be betterHashmapSlightly inferior, but this exception:LinkedhashmapCollection viewSizeProportional.HashmapThe iteration time is likely to be costly because it requires timeCapacityProportional.
The link hash ing has two parameters that affect its performance:Initial CapacityAndLoad Factor. Their definition andHashmapExtremely similar. Note that the effect of selecting a very high value for the initial capacity on this class is compared.HashmapSmall because the iteration time is not affected by the capacity.
<Span style = "font-size: 18px;"> Import Java. util. linkedhashmap; import Java. util. map; public class lrucache extends hashmap <integer, integer> {private int capacity; Public lrucache (INT capacity) {super (capacity, 0.75f, true); this. capacity = capacity;} // rewrite the parent class get. If the value is null, the range is-1 Public integer get (Object key) {INTEGER v = super. get (key); If (V! = NULL) return V; else return-1;} // rewrite the parent class method. When the cache capacity is exceeded, the public Boolean removeeldestentry (map. entry <integer, integer> eldest) {return size ()> capacity;} public void set (INT key, int value) {super. put (Key, value) ;}</span>
Implement LRU cache using linkedhashmap