Java:用于缓存计算结果的数据结构?

标签 java caching map tuples computation

我有一个昂贵的计算,我想缓存它的结果。有没有办法用两个键制作 map ?我在想类似 Map<(Thing1, Thing2), Integer> 的东西.

然后我可以检查:

if (! cache.contains(thing1, thing2)) {
  return computeResult();
}
else {
  return cache.getValue(thing1, thing2);
}

伪代码。但也有类似的东西。

最佳答案

您需要创建一个包含 Thing1 和 Thing2 的类,例如:

class Things {
    public final Thing1 thing1;
    public final Thing2 thing2;
    public Things(Thing1 thing1, Thing2 thing2) {
      this.thing1 = thing1; 
      this.thing2 = thing2;
    }
    @Override
    public boolean equals(Object obj) { ... }
    @Override
    public int hashCode() { ... };
 }

然后使用它:

Things key = new Things(thing1, thing2);
if (!cache.contains(key) {
    Integer result = computeResult();
    cache.put(key, result);
    return result;
} else {
    return cache.getValue(key);
}

请注意,您必须实现 equals 和 hashcode 才能使此代码正常工作。如果您需要此代码是线程安全的,请查看 ConcurrentHashMap。

关于Java:用于缓存计算结果的数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1552403/

相关文章:

java - CHM 没有 ConcurrentModificationException。为什么?

view - Pouchdb如何使用键来细化查询?

c++ - error C2678 : binary '<' : no operator found which takes a left-hand operand. ..(或者没有可接受的转换)

java - 是否可以从Spring的application.properties中获取对象数组?

Java读取包含日文字符的文件

java - 结果集和 SQL 函数

java - 缓存类似集合的集合

python - 在内存中缓存 MySQLdb 数据库查询的结果

java - 返回mysql的thread_id

ios - 网络照片应用程序缓存(Nimbus)