How does java type inference work?

本秂侑毒 提交于 2019-12-01 06:13:32

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.

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