I understand that the intricacies of Java generics can get... intricate. I figure that if I have a Google Guava multimap with a Collection<? extends FooBar>
, I should be able to use getMap()
to assign that to a Map<String, ? extends FooBar>
. But I can't do that in Eclipse 4.4RC2; it tells me, "Type mismatch: cannot convert from Map<String,Collection<capture#1-of ? extends EclipseGenerics.FooBar>>
to Map<String,Collection<? extends EclipseGenerics.FooBar>>
".
import java.util.*;
import com.google.common.collect.*;
public class EclipseGenerics {
public static interface FooBar {
public String getFoo();
}
public static <FB extends FooBar> SetMultimap<String, FB> groupFooBarByBar(final Iterable<FB> foobars) {
final SetMultimap<String, FB> groupedFoobars = HashMultimap.create();
for (final FB foobar : foobars) {
groupedFoobars.put(foobar.getFoo(), foobar);
}
return groupedFoobars;
}
public static void test() {
Collection<FooBar> foobars = new ArrayList<>();
final SetMultimap<String, ? extends FooBar> groupedFooBars = groupFooBarByBar(foobars);
//why can't I do this?
final Map<String, Collection<? extends FooBar>> map = groupedFooBars.asMap();
}
}
I cannot do this:
final Map<String, Collection<? extends FooBar>> map = groupedFooBars.asMap();
Why not? asMap()
should return Map<K,Collection<V>>
.
But I can do this!
final Map<String, ? extends Collection<? extends FooBar>> map = groupedFooBars.asMap();
I get a similar error with Oracle's Java 1.8 javac compiler, so either Eclipse 4.4RC2 and Oracle are both wrong, or (more likely) I'm still not a complete expert on Java generics.
Anyone care to explain why Map<String, Collection<? extends FooBar>>
doesn't work, but Map<String, ? extends Collection<? extends FooBar>>
does work?