How does java type inference work?

时光总嘲笑我的痴心妄想 提交于 2019-12-30 10:05:19

问题


Can someone please explain how the following syntax works?

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

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

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?

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


回答1:


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.

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

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.



来源:https://stackoverflow.com/questions/31508838/how-does-java-type-inference-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!