【问题标题】:Testing the algorithm using Linkedhashmap使用 Linkedhashmap 测试算法
【发布时间】:2019-12-24 17:26:39
【问题描述】:

下午好。我想测试一下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 对象。 我想也许你需要从一张地图复制到另一张地图,但它会大于指定的大小。

由于知识面小,我知道在某个地方犯了一个愚蠢的错误,请告诉我如何正确地做或举个例子。

【问题讨论】:

  • 您的 addToMap() 方法没有意义:您总是将相同的、唯一的 Element 对象添加到地图中。阅读stackoverflow.com/questions/40480/…。它也应该是私有的,否则任何人都可以在地图中添加尽可能多的条目。
  • @jb-nizet 好的,谢谢。我会解决的。但我还有一个问题。我如何进行比较
  • LRUCache 也不可能等于 LinkedHashMap。这些不是同一类的实例。您需要比较具有可比性的事物。
  • @JBNizet 我可以从 Linkedhashmap 扩展吗?
  • 不,你真的,真的不应该那样做。目前,您的 LRUCache 是无用的:您可以向其中添加内容,但不能从中获取任何内容。添加允许获取它包含的内容的方法(键集,每个键的值),然后测试它包含的内容是否是您期望的内容。

标签: java algorithm junit linkedhashmap


【解决方案1】:

您的“LRUCache”类没有实现 hashCodeequals 所以测试行:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多