Skip to content

Instantly share code, notes, and snippets.

@LDuncAndroid
Created April 16, 2021 20:39
Show Gist options
  • Save LDuncAndroid/13bbf3414de5cf9aaf4db300fd1a3e70 to your computer and use it in GitHub Desktop.
Save LDuncAndroid/13bbf3414de5cf9aaf4db300fd1a3e70 to your computer and use it in GitHub Desktop.
LRU Cache
class LRUCache(capacity: Int) {
private val internalCache: LinkedHashMap<Int, Int> =
object : LinkedHashMap<Int, Int>(initialCapacity = capacity, loadFactor = 0.75f, accessOrder = true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Int, Int>?): Boolean {
return size > capacity
}
}
fun get(key: Int) = internalCache.getOrDefault(key, -1)
fun set(key: Int, value: Int) = internalCache.putIfAbsent(key, value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment