How does java type inference work?

前端 未结 1 1650
梦如初夏
梦如初夏 2021-01-13 20:43

Can someone please explain how the following syntax works?

public static  HashMap getMap(){
    return new HashMap();
}
         


        
相关标签:
1条回答
  • 2021-01-13 21:02

    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.

    0 讨论(0)
提交回复
热议问题