LinkedHashMap implements LRU cache cache mechanism, Kotlin
After the accessOrder=true of LinkedHashMap, access the element stored in LinkedHashMap, LinkedHashMap will move the element to the end. Using this, you can set a cache upper limit. When the stored cache exceeds the upper limit, just delete the LinkedHashMap header element (because the header means that it has not been used much).
As for deleting the top element, we can write code ourselves to find out the top (first) element and delete it. However, it just so happens that the internal source code implementation of LinkedHashMap has a function:
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
It returns false by default. If the function returns true, LinkedHashMap will delete the oldest value in the head. Dynamically judge in the code whether the currently stored elements exceed the upper limit of the cache, and return true if it exceeds, and let LinkedHashMap delete the top (oldest) value.
import java.util.LinkedHashMap
class Lru(
initialCapacity: Int,
loadFactor: Float,
accessOrder: Boolean
) : LinkedHashMap<Int, String>(initialCapacity, loadFactor, accessOrder) {
private val CACHE_LIMIT: Int = 3
//accessOrder=true改变LinkedHashMap的存储策略
constructor() : this(10, 0.75F, true)
//如果当前的map尺寸大于缓存上限
//删除最老的元素。
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Int, String>?): Boolean {
return size > CACHE_LIMIT
}
}
fun main(args: Array<String>) {
val map = Lru()
map[1] = "A"
map[2] = "B"
map[3] = "C"
println(map)
println("-")
//插入D后,最头的A被删除。
println("插入D")
map[4] = "D"
println(map)
println("-")
//插入E后,最头的B被删除。
println("插入E")
map[5] = "E"
println(map)
println("-")
println("访问C")
println(map[3])
println(map)
}
Deliberately set a maximum of 3 elements to be cached, and see the result of the code running:
{1=A, 2=B, 3=C}
-
insert D
{2=B, 3=C, 4=D}
-
insert E
{3=C, 4=D, 5=E}
-
access C
C
{ 4=D, 5=E, 3=C}