Good afternoon. I want to test the LRU algorithm.
My implementation of LRU:
public class LRUCache {
private int capacity;
private LinkedHashMap<Integer, Element> cacheMap = new LinkedHashMap<Integer, Element>(0, 0.75f, true);
public LRUCache(int capacity) {
this.capacity = capacity;
}
private Element newEntity = new Element();
public void put(int key, String value) {
if (cacheMap.size() == capacity) {
Map.Entry<Integer, Element> element = cacheMap.entrySet().iterator().next();
int tempKey = element.getKey();
cacheMap.remove(tempKey);
addToMap(key, value);
} else {
addToMap(key, value);
}
}
public void addToMap(int key, String value) {
newEntity.setValue(value);
cacheMap.put(key, newEntity);
}
}
Test:
LRUCache actualList = new LRUCache<>(2);
LinkedHashMap<Integer, String> expectedList = new LinkedHashMap<>();
@Test
public void test(){
actualList.put(1, "a");
actualList.put(2, "b");
actualList.put(3, "c");
expectedList.put(2, "b");
expectedList.put(3, "c");
Assert.assertEquals(expectedList, actualList);
}
I've tried converting my actualList to map in LRUCache :
public LinkedHashMap converter() {
return new LinkedHashMap(cacheMap);
}
But in all my attempts to transform my algorithm, a new Linkedhashmap object is created each time. I thought maybe you need to copy from one map to another, but then it will be larger than the specified size.
Due to the small Luggage of knowledge, I know that make somewhere a stupid mistake, please tell me how to do it properly or point to an example.
Your 'LRUCache' class doesn't implement hashCode
or equals
so the test line:
Assert.assertEquals(expectedList, actualList);
is using the default Object
implementation which will be returning false
.
Perhaps you mean to make LRUCache
a subclass of AbstractMap
, or if you don't need that, just have your test compare the internal contents cacheMap
with the expected contents.