package com.abhishek.dojo.lru;
import java.util.Iterator;
import java.util.LinkedHashMap;
public class LRUCache {
private int capacity;
// use linkedhashmap to maintain the sequence
private LinkedHashMap<Integer, Integer> map;
public BetterLRUCache() {
// TODO Auto-generated constructor stub
}
public BetterLRUCache(int capacity, LinkedHashMap<Integer, Integer> map) {
this.capacity = capacity;
this.map = map;
}
public int get(int k) {
// check if key exists, if no return -1
// if yes, then send the key through put function so that it can be 'reinserted'
if (this.map.get(k) == null) {
return -1;
}else {
this.put(k, value);
}
// once done, return the key
return this.map.get(k);
}
// all get operations should go through put function
public void put(int k, int v) {
if (map.containsKey(k)) {
this.map.remove(k);
}else if (map.size() == this.capacity){
// be sure to remove first element as its the oldest element in collection
Iterator<Integer> iterator = this.map.keySet().iterator();
iterator.next();
iterator.remove();
}
map.put(k, v);
}
}