Oliver Hausler
Oliver Hausler

Reputation: 4977

Cast the value in a Map

I am using memcache (Google App Engine) and use getAll() to retrieve several cache entries in a batch. My cache entries are:

private Map<String, Set<Long>> cacheEntries; // key: String, value: Set<Long>

getAll() returns Object as value (because it doesn't know I have cached a Set previously), here is the signature:

<T> java.util.Map<T,java.lang.Object> getAll(java.util.Collection<T> collection);

In my code I go:

cacheEntries = cache.getAll(keys); // cache is the MemcacheService, keys is a Collection of String

which obviously fails because Object is returned and Set is expected. So I tried to cast the map like this:

cacheEntries = (Map<String, Set<Long>>) cache.getAll(keys);

but the compiler tells me

Incompatible types, cannot cast Map<String, Object> to Map<String, Set<Long>

It is clear why: I am trying to cast the whole Map while I really need to cast the value in each map entry.

Sure I could solve this by iterating over the Map and casting each value separately, but I'd like to know if there is a better way to achieve that.

Upvotes: 2

Views: 1657

Answers (1)

Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15507

You can cast it to raw Map before casting to Map<String, Set<Long>>:

cacheEntries = (Map<String, Set<Long>>)(Map)cache.getAll(keys);

You could also use Map<String, ?> if you don't want the raw type warning.

Upvotes: 3

Related Questions