Guest User

Untitled

a guest
Dec 10th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. import java.util.LinkedHashMap
  2.  
  3. class LRUCache<K : Any, V : Any>(
  4. val capacity: Int,
  5. val onRemove: (key: K, value: V) -> Unit = { _, _ -> }
  6. ) {
  7. private val map: LinkedHashMap<K, V> = LinkedHashMap(capacity+1, 1f, true)
  8.  
  9. operator fun get(key: K): V? {
  10. return map[key]
  11. }
  12.  
  13. operator fun set(key: K, value: V) {
  14. map[key] = value
  15.  
  16. if (map.size > capacity) {
  17. val removedKey = map.keys.iterator().next()
  18. val removedValue = requireNotNull(map.remove(removedKey))
  19. onRemove(removedKey, removedValue)
  20. }
  21. }
  22. }
Add Comment
Please, Sign In to add comment