Java generics grammar
I could not understand the following statement, although it is indeed compileable:
List<Integer> l = Collections.<Integer>singletonList(5);
Tell me, second <Integer>
, how can we put one <Integer>
before the method name? I suspect this is a generics ad but can't find it anywhere. But I only know the definition, for example List<Integer>
put <Integer>
for type generics. Can anyone point me to a tutorial for this grammar or find a duplicate question (sorry I didn't find it during my quick search)?
Many thanks!
source to share
This is called the type witness and is referenced in the Type Inference trail :
A generic method
addBox
defines one type of parameter named U. Typically, the Java compiler can infer parameters of the type of a call to a generic method. Hence, in most cases, you do not need to specify them. For example, to call a generic methodaddBox
, you can specify a type parameter with a witness type like this:
BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);
In fact, a type witness allows the developer to resolve cases where the type mechanism cannot correctly determine which type will have a value. You will see its use more widely and more widely in Java 7, whereas Java 8 has improved its type inference.
source to share