Javac cannot infer type without helper variable

I came across a java compiler behavior (jdk1.6.0_45) which I cannot explain. Here are two pieces of code - the first is compiled, and the second is not. Makes up:

Map<String, Collection<MyClass>> result = Maps.newHashMap();

Comparator<? super MyClass> comparator = comparatorProvider.getComparator(*some parameter*);
TreeMultiset<MyClass> multiSet = TreeMultiset.create(comparator);
result.put("blahBlah", multiSet);

Not compiling:

Map<String, Collection<MyClass>> result = Maps.newHashMap();

Comparator<? super MyClass> comparator = comparatorProvider.getComparator(*some parameter*);
result.put("blahBlah", TreeMultiset.create(comparator));

Maps and TreeMultiset classes are part of the Google-Guava libraries.

The second fragment will not compile, resulting in the following error:

put(java.lang.String,java.util.Collection<MyClass>) in java.util.Map<java.lang.String,java.util.Collection<MyClass>> cannot be applied to (java.lang.String,com.google.common.collect.TreeMultiset<java.lang.Object>)

Note that java.lang.Object is part of the error. Thus, it seems that javac could not infer the TreeMultiset type without the explicit "multiset" variable.

Here is the factory method code:

@SuppressWarnings("unchecked")
public static <E> TreeMultiset<E> create(
  @Nullable Comparator<? super E> comparator) {
return (comparator == null)
       ? new TreeMultiset<E>((Comparator) Ordering.natural())
       : new TreeMultiset<E>(comparator);
}

Any clarity in this behavior will be truly appreciated.

Even the IDE (Intellij IDEA) does not give errors.

+4
1

Java , ( , , Scala). :

result.put("blahBlah", TreeMultiset.<MyClass>create(comparator));
+3

All Articles