簡體   English   中英

沒有輔助變量,Javac無法推斷出類型

[英]Javac cannot infer the type without auxiliary variable

我遇到了java編譯器(jdk1.6.0_45)的行為,我無法解釋。 這是兩個代碼片段 - 第一個編譯,而第二個不編碼。 編譯:

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);

不編譯:

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

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

Maps和TreeMultiset類是Google-Guava庫的一部分。

第二個片段無法編譯,給出以下錯誤:

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>)

注意java.lang.Object部分錯誤。 因此,似乎javac無法在沒有明確的“multiset”變量的情況下推斷TreeMultiset的類型。

這是工廠方法的代碼:

@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);
}

對此行為的任何澄清都將非常感激。

甚至IDE(Intellij IDEA)也沒有錯誤。

Java類型推斷沒有我們想要的那么強(與Scala相比)。 您可以在沒有輔助變量的情況下提供相同類型的參數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM