Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,?,?,?,?,?>() )
like image 899
Sebastien Lorber Avatar asked Jun 08 '12 08:06

Sebastien Lorber


People also ask

What is generic method in Java?

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

What is generics in Java with example?

Generics add that type of safety feature. We will discuss that type of safety feature in later examples. Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well.

Why are generics used in Java Mcq?

Why are generics used? Explanation: Generics add stability to your code by making more of your bugs detectable at compile time.


1 Answers

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.

like image 140
Péter Török Avatar answered Oct 17 '22 03:10

Péter Török