I found a ‘unusual’ generic syntax such as:
Arrays.<String>asList(...);
Collections.<String>emptyList();
Obviously, the results of the methods are generic. Is such syntax for type checking? An Object array cannot be an argument to Arrays.<String>asList(...).
<typearg>methodnameis the syntax for explicitly specifying the type argument for a generic methodWhen you use a generic class, you usually have to specify the type argument (e.g.
String):With a generic method, you don’t usually pass a type argument:
You’ll notice no where did we did the code explicitly specify we want the
Stringversion offoo, i.e. there was no explicit type argument<String>specified like we saw when using a generic class (List<String>).The compiler is doing some compiler magic to infer the generic type argument based on context. This is a great thing and very powerful.
However, occassionally the compiler can’t infer the type arguments automatically:
What concrete version of
barare we trying to invoke, i.e. what is the type argument for this call? Well, the compiler doesn’t either. We have to explicitly state the type argument, just like we normally do when using a generic class:Also see:
Aside: it may be worth mentioning that the Java 7 will be adding the so-called diamond operator to allow us to have the compiler to infer the type arguments when using generic classes now too:
becomes
What is the point of the diamond operator (<>) in Java 7?