java类型推断如何工作? [英] How does java type inference work?

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

问题描述

有人可以解释以下语法的工作原理吗?

Can someone please explain how the following syntax works?

public static <K, V> HashMap<K, V> getMap(){
    return new HashMap<K, V>();
}

如果这个方法是在我的一个不可实例化的util类中实现的话拥有这个可以用作静态工厂方法来创建地图实例,对吧?

As in, if this method was implemented in a non instantiable util class of my own this can be used as a static factory method to create map instances, right?

Map<Integer, String> myMap = MyUtil.getMap();

然后会返回一个新的HashMap,其中包含整数键和字符串值,是吗?
如果是这样,编译器和VM如何实现地图的键和条目类型?

would then return a new HashMap with Integer keys and String values for its entries, am I right? If so, how are the types of the key and entry of map being realized by the compiler and VM?

如果有人能解释如何,我真的很感激Java就是这么做的。

I would really appreciate if someone could explain how Java does this.

推荐答案

你问'Java如何做到这一点'。 Java是在语言规范中定义的,该规范没有规定如何实现规范。所以选择解决方案真的取决于实现。因此,如果您真的想知道特定编译器或解释器如何实现类型推断,我怀疑需要熟悉该工具的人员解决。

You ask 'how Java does this'. Java is defined in a language specification which does not dictate how the specification is implemented. So it's really up to the implementation to pick a solution. So if you really want to know how a particular compiler or interpreter implements type inference I suspect that will need to be addressed by people familiar with that tool.

如果您的问题是真的有什么规则然后你会发现它们在规范本身,以及 Java API文档,以及标准Java教程(正式程度越来越低)。

If your question is really 'what are the rules' then you'll find they are explained pretty well in the specification itself, and in the Java API documentation, and in the standard Java tutorial (in decreasing levels of formality).

这是一个非常复杂的领域,需要处理许多棘手的案件 - 实际上它涉及三个正确理解的过程(减少,合并和解决)。但是,如果您正在寻找一个简单的摘要,我会将其声明为在实例化类或方法时,用尽可能最具体的类型替换每个泛型类型。在您的情况下,用整数 V 替换 K code> String 是最有意义的推断。

It's a pretty complex area with lots of knarly cases to handle - in fact it involves three processes to understand properly (reduction, incorporation and resolution). But if you are looking for a simple summary I would state it as "when instantiating a class or method, replace each generic type with the most specific type possible". In your case replacing K with Integer and V with String is the the most specific inference that makes sense.

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

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