【问题标题】:Getting error on passing Collections.emptyMap as an argument将 Collections.emptyMap 作为参数传递时出错
【发布时间】:2018-04-16 00:54:07
【问题描述】:

我不明白为什么在将Collections.emptyMap() 分配给地图引用时将Collections.emptyMap() 作为参数传递时出现错误,但没有提供错误,下面是我尝试的代码示例,我使用的是JDK1。 7

public class Solution {
    public static void main(String[] args) {
        Solution sol = new Solution();
        Map<String, String> map = Collections.emptyMap(); //There is no compile time error on this.
        sol.calculateValue(Collections.emptyMap()); //Getting compile time error on this
    }

    //what is the difference in passing Collections.emptyMap() as a parameter
    public void calculateValue(Map<String, String> pMap) {

    }
}

【问题讨论】:

  • 我似乎记得 Java 1.7,在某些情况下泛型类型推断存在问题。在return (x != null ? x : Collections.emptyMap()) 之类的地方使用它也会出现类似的问题,也无法编译。
  • 我觉得看到了一些信息in this answer about Collections.emptyList()

标签: java generics collections


【解决方案1】:

因为您使用的是 JDK 1.7,所以您无法从 JDK 8 及更高版本中改进的类型推断中受益。最好更新您正在编译的 Java 版本。如果这不是一个选项,那么在将 Collections#emptyMap 作为参数传递时,您必须将 Map 的参数显式传递给函数:

calculateValue(Collections.<String, String>emptyMap());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多