Nelson.b.austin
Nelson.b.austin

Reputation: 3190

Android LRUCache Retrieval

I have implemented a standard LRUCache in Android that stores Objects. Each key is a unique ObjectId associated with the Object stored. My problem is that the only way to retrieve an Object from cache is by the ObjectId (no iterator). What would be the best way to implement a getAll() method? Another option would be to store all the ObjectIds in a list somewhere, so I can iterate over the lists and get all of the Objects - but what would be the best way of holding all of the ObjectIds?

Thanks!

Upvotes: 5

Views: 3901

Answers (3)

tu4n
tu4n

Reputation: 4450

Using snapshot to get current collection at the moment

lruCache.snapshot().values()

Upvotes: 5

Michiyo
Michiyo

Reputation: 1201

If you're using (or extending) the LruCache that Android provides, it has a snapshot method that returns a map of keys (your ObjectIds) and values (your Objects). You can do something like this:

Map<ObjectIds, Object> snapshot = lruCache.snapshot();
for (ObjectIds id : snapshot.keySet()) {
  Object myObject = lruCache.get(id);
}

If you're not using Android's LruCache, then I imagine it would depend on your implementation. (I'd also be curious what motivated you to implement your own instead of subclassing the provided one!)

Upvotes: 6

SimonSays
SimonSays

Reputation: 10977

It does not make sense to iterate over the objects in a LRU cache. You can not know which object is still in the cache and which got evicted (you actually can, but that's another story). It sound like you'd probably better off with a different data structure like a Hashmap or so. Nothing will ever get evicted from there.

A common use-case is to have a List of all possible object keys in memory. If you need one, you check if it is in the cache. If not, receive it and add it to the cache.

Upvotes: -1

Related Questions