I’m trying to use Guava to simulate a LRU map.
Map<K, V> map = CacheBuilder.newBuilder()
.maximumSize(maxSize)
.build() // not using a cache loader
.asMap();
But when I try do this I get an error.
Type mismatch: cannot convert from ConcurrentMap<Object,Object> to Map<K,V>
However, if I create the Map with a temporary reference to the cache it works fine.
Cache<K, V> cache = CacheBuilder.newBuilder()
.maximumSize(maxSize)
.build();
Map<K, V> map = cache.asMap();
Why does this work and the first sample doesn’t?
It’s Java’s generics fault – generic types cannot be inferred in this case. You should add
<K, V>to tell Java to treat newly created cache asCache<K, V>, notCache<Object, Object>.and then it’ll work:
See this part of Angelika Langer’s Java Generics FAQs.