From a official Java JDK1.7 guide, I got this quote, but I don't understand how it works. Can anyone explain? In other words, how does the diamond infer a Integer type when its passed an empty String?
MyClass<Integer> myObject = new MyClass<>("");
In this example, the compiler infers the type Integer for the formal type parameter, X, of the generic class MyClass. It infers the type String for the formal type parameter, T, of the constructor of this generic class.
The Integer
part is inferred from the usage of the result of the constructor call - it's assigning to a variable of type MyClass<Integer>
, hence the Integer
part is inferred for the diamond. The constructor argument is irrelevant to this (unless it had to be the same type, in which case you'd just get a compilation error.)
Basically, if the type argument is clear from the context in which the expression is used (where "clear" means "following precise rules" of course) then the compiler will infer it.
See more on this question at Stackoverflow