3

I couldn't understand the following statement while it is indeed compilable:

List<Integer> l = Collections.<Integer>singletonList(5);

Say, the second <Integer>, how can we put a single <Integer> in front of the method name? I suspect it's a declaration of generics but cannot find it anywhere. But I only know the definition such as List<Integer>, put <Integer> behind a generics type. Can anybody point out me a tutorial for this grammar or find the duplicated question (sorry I didn't find one during my quick search)?

Many thanks!

zzy
  • 751
  • 1
  • 13
  • 25

1 Answers1

3

This is called a type witness, and it is referenced in the Type Inference trail:

The generic method addBox defines one type parameter named U. Generally, a Java compiler can infer the type parameters of a generic method call. Consequently, in most cases, you do not have to specify them. For example, to invoke the generic method addBox, you can specify the type parameter with a type witness as follows:

BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);

Effectively, a type witness lets the developer step in to resolve cases in which the type engine can't properly infer what type a value will result in. You'd see its usage more commonly and prevalently in Java 7, whereas Java 8 has improved its type inference capabilities.

Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230