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 quote indicates that there is a generic constructor in your class, which declares it's own type parameter. This is similar to how you create a generic method. The type parameter for the constructor is inferred from the argument you are passing while instantiating the class.
Here is a simple version of a class that matches that invocation:
Now when you instantiate your class as in your code, the type parameter
T
is inferred asInteger
, and type parameterS
in constructor is inferred asString
, from the argument you passed.As for the diamond operator, from Java 7 onwards, you don't need to give the type arguments on while creating an instance of a generic class if you already are assigning a reference to a reference. The type argument will be inferred from the one used with the reference type, here
Integer
.