使用 Linkedhashmap 测试算法

Testing the algorithm using Linkedhashmap

下午好。我想测试一下LRU算法

我的 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);
    }

}

测试:

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);

}

我已经尝试将我的 actualList 转换为 LRUCache 中的映射:

public LinkedHashMap converter() {
    return new LinkedHashMap(cacheMap);
}

但在我对算法进行的所有尝试中,每次都会创建一个新的 Linkedhashmap 对象。 我想也许你需要从一张地图复制到另一张地图,但它会大于指定的大小。

由于知识渊博,我知道在某处犯了一个愚蠢的错误,请告诉我如何正确地做或指出一个例子。

你的 'LRUCache' class 没有实现 hashCodeequals 所以测试行:

Assert.assertEquals(expectedList, actualList); 使用默认的 Object 实现,它将返回 false.

也许您的意思是让 LRUCache 成为 AbstractMap 的子 class,或者如果您不需要,只需让您的测试比较内部内容 cacheMap 与预期的内容。