我有一个昂贵的计算,我想缓存它的结果。有没有办法用两个键制作 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/