publicMyCache(int capacity){ if (capacity < 1){ thrownew RuntimeException("should be more than 0."); } this.keyNodeMap = new HashMap<>(); this.nodeList = new NodeDoubleLinkedList<>(); this.capacity = capacity; }
public V get(K key){ if (this.keyNodeMap.containsKey(key)){ Node<K,V> res = this.keyNodeMap.get(key); this.nodeList.moveNodeToTail(res); return res.value; } returnnull; }
publicvoidset(K key, V val){ if (this.keyNodeMap.containsKey(key)){ Node<K,V> node = this.keyNodeMap.get(key); node.value = val; this.nodeList.moveNodeToTail(node); }else { Node<K,V> newNode = new Node<>(key, val); this.keyNodeMap.put(key, newNode); this.nodeList.addNode(newNode); if (this.keyNodeMap.size() == this.capacity +1){ this.removeMostUnusedCache(); } } }