如何在这里推断泛型? [英] How is the generic type getting inferred here?

查看:92
本文介绍了如何在这里推断泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static void main(String [] args){
Map< String,Map< Long,List< String>>>> map = getHashMap();
}

static< K,V>地图< K,V> getHashMap()
{
返回新的HashMap< K,V>();
}

我在google guava中看到了一个类似的代码(和工厂方法一样)没有提到泛型类型。我不明白泛型如何被上面的程序推断出来。我的意思是getHashMap函数如何理解map的类型,因为我没有向函数传递任何类型的信息。

解决方案

getHashMap 函数不必推断类型。 Java语言规范要求javac推断类型同意( 15.12.2.7根据实际参数推断类型参数)。我相信当前对于JDK7来说,计划仍然是支持钻石操作者的,所以这类事情也可以在 new 的情况下工作,尽管它有一些明显无意义的语法。

 地图< String,Map< Long,List< String>>> map = new HashMap<>(); 
^^ diamond


public static void main(String[] args) {
    Map<String, Map<Long, List<String>>> map = getHashMap();
}

static <K,V> Map<K,V> getHashMap()
{
    return new HashMap<K, V>();
}

I saw a similar code in google guava (as factory methods) for making instances of Hashmap without mentioning the generic types.I don't understand how the generic is getting inferred by the above program.I mean how can the function getHashMap understand the type of map since i'm not passing any type information to the function.

解决方案

The getHashMap function does not have to infer the types. It's at the call site that javac is required by the Java Language Spec to infer that the types agree (15.12.2.7 Inferring Type Arguments Based on Actual Arguments).

I believe the current plan is (still) for JDK7 to support the diamond operator, so this sort of thing will work with new too, although with a bit of apparently pointless syntax.

Map<String, Map<Long, List<String>>> map = new HashMap<>();
                                                      ^^diamond

这篇关于如何在这里推断泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆