Search code examples
javagenericstype-inferencescjp

What's this generics usage in Java? X.<Y>method()


I've read the whole SCJP6 book Sierra and Bates book, scored 88% the exam.

But still, i never heard of how this kind of code works as it's not explained in the generics chapter:

Collections.<TimeUnit>reverseOrder()

What is this kind of generics usage? I discovered it in some code but never read anything about it. It seems to me it permits to give some help to type inference. I've tried to search about that but it's not so easy to find (and it's not even in the SCJP book/exam!)

So can someone give me a proper explaination of how it works, which are all the usecases etc?

Thanks


Edit Thanks for the answers but i expected more details :) so if someone want to add some extra informations:

What about more complex cases like

  • Using a type declared in class , can i do something like Collections.<T>reverseOrder() for exemple?
  • Using extends, super?
  • Using ?
  • Giving the compiler only partial help (ie O.manyTypesMethod<?,MyHelpTypeNotInfered,?,?,?,?,?>() )

Solution

  • It is explicit type specification of a generic method. You can always do it, but in most cases it's not needed. However, it is required in some cases if the compiler is unable to infer generic type on its own.

    See an example towards the end of the tutorial page.

    Update: only the first of your examples is valid. The explicit type argument must be, well, explicit, so no wildcards, extends or super is allowed there. Moreover, either you specify each type argument explicitly or none of them; i.e. the number of explicit type arguments must match the number of type parameters of the called method. A type parameter such as T is allowed if it is well defined in the current scope, e.g. as a type parameter of the enclosing class.