我正在使用内存缓存(Google App Engine),并使用getAll()批量检索几个缓存条目。我的缓存条目是:
private Map<String, Set<Long>> cacheEntries; // key: String, value: Set<Long>
getAll()返回Object作为值(因为它不知道我之前已经缓存过Set),这是签名:
<T> java.util.Map<T,java.lang.Object> getAll(java.util.Collection<T> collection);
在我的代码中,我去了:
cacheEntries = cache.getAll(keys); // cache is the MemcacheService, keys is a Collection of String
这显然是失败的,因为返回了Object并期望Set。所以我试图像这样投射地图:
cacheEntries = (Map<String, Set<Long>>) cache.getAll(keys);
但是编译器告诉我
Incompatible types, cannot cast Map<String, Object> to Map<String, Set<Long>
显而易见的原因:我确实在强制转换每个Map条目中的值时尝试转换整个Map。
当然,可以通过遍历Map并分别转换每个值来解决此问题,但是我想知道是否有更好的方法来实现。
您可以Map
先将其转换为raw,然后再转换为Map<String, Set<Long>>
:
cacheEntries = (Map<String, Set<Long>>)(Map)cache.getAll(keys);
Map<String, ?>
如果您不想要原始类型警告,也可以使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句