檢出Guava,Google提供的一個有用的實用程序庫,它包含一些很棒的緩存功能。特別是,它支持最大尺寸,並自動處理驅逐。
對於2個鍵問題,爲什麼不與其它類,它的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
}
}
}
感謝您對所有人的迴應......我看着番石榴,但驅逐過程並不適合我們。因爲我們需要根據規模驅逐,但不是所有東西,而只是最早的記錄。另外我應該在我的第二把鑰匙上澄清。我需要的值的方式是鍵2>輸入鍵。用戶將提供輸入鍵1和輸入鍵2.但返回的值應等於輸入鍵1並大於輸入鍵2。 – user1712512