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

Nic*_*ner 2 java caching tuples map computation

我有一个昂贵的计算,其结果我想缓存.有没有办法用两把钥匙制作地图?我在想类似的东西Map<(Thing1, Thing2), Integer>.

然后我可以检查:

if (! cache.contains(thing1, thing2)) {
  return computeResult();
}
else {
  return cache.getValue(thing1, thing2);
}
Run Code Online (Sandbox Code Playgroud)

伪代码.但是那些方面的东西.

Dea*_*vey 5

您需要创建一个包含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() { ... };
 }
Run Code Online (Sandbox Code Playgroud)

然后使用它:

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

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