Search code examples
javagenericsguava

How to create a synchronized multimap with Guava in one line?


This works:

Multimap<String, String> m = HashMultimap.create();

Also this works:

Multimap<String, String> m = HashMultimap.create();
Multimap<String, String> n = Multimaps.synchronizedMultimap(m);

But why does this not work?

Multimap<String, String> n = Multimaps.synchronizedMultimap(HashMultimap.create());

I get an error:

Type mismatch: cannot convert from Multimap Object,Object to Multimap String,String

I tried to add the <> in many places but had no success. What do I do wrong?

I am still stuck with Java 7.


Solution

  • You can use an explicit type hint for create:

    Multimap<String, String> n = Multimaps.synchronizedMultimap(
        HashMultimap.<String, String>create());
    

    Java 8 had some type inference changes, so it works fine there without the hint.