我刚刚发现 Guava Caching,我看到的所有示例都使用映射、键和值。
有没有办法将 Guava 缓存用于ArrayList?
我有一个包含元素的 ArrayList,每个元素有 60 秒的生存时间,之后应该将其删除,我感谢任何建议。
删除每个元素后是否可以触发一个方法?例如,如果一个数字从列表中删除,我需要再次重新计算平均值。
最佳答案
Is there any way to use guava cache for an ArrayList?
Guava Cache 被设计为通过键查询。但是,您可以使用 ArrayList
的索引作为键或选择对象的某些唯一属性作为键(尽管据我了解,您需要按照添加值的顺序存储值)。
And is it possible to trigger a method after removal of each element?
是的,在构建您的 Cache<K, V>
时,设置 RemovalListener<K,V>
。
例如:
Cache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterWrite(60, TimeUnit.SECONDS)
.removalListener(new RemovalListener<String, String>() {
public void onRemoval(RemovalNotification<String, String> removal) {
// Compute the average here
}
})
.build();
关于java - 如何使用带有过期时间的 Guava Cache 的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898103/