查看Guava,这是 Google 提供的一个有用的实用程序库,其中包含一些出色的缓存功能。特别是,它支持最大大小,并将自动处理驱逐。
至于 2 键问题,为什么不将 Guava 缓存(或任何实现)包装在另一个类中,该类采用 2 键并从组合中生成单个键,例如:
public class MyCache<Key, Value> {
private final Cache<CacheKey, Value> guavaCache = CacheBuilder.build()
public void put(Key keyOne, Key keyTwo, Value value) {
cache.put(new CacheKey(keyOne, keyTwo), value);
}
public Value get(Key keyOne, Key keyTwo) {
return cache.getIfPresent(new CacheKey(keyOne, keyTwo));
}
private static final class CacheKey {
private final Key keyOne;
private final Key keyTwo;
CacheKey(Key keyOne, Key keyTwo) {
this.keyOne = keyOne;
this.keyTwo = keyTwo;
}
@Override
public int hashCode() {
int hash = keyOne == null ? 0 : keyOne.hashCode();
return hash + 31 * keyTwo == null ? 0 : keyTwo.hashCode();
}
@Override
public boolean equals(Object o) {
// implementation omitted
}
}
}