Reputation: 14970
I am new to java.I was going through a tutorial on java generics.
Java Generics tutorial There is a section about declaring generic methods and constructors.
Methods and constructors can be generic if they declare one/more type variables.
public static <T>T getFirst (List<T> list)
This method accepts a reference to List and will return an object of type T.
why is there a T after static? Is this a printing mistake.?
What does that mean?
I am a beginner in java an new to the concepts of generics.
Upvotes: 1
Views: 174
Reputation: 5754
Why is there a T after static? Is this a printing mistake? What does that mean?
The <T>
after "static" means the method is a generic method. From that link:
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.
The way to define a generic method is to specify the type parameters (ex: <T>
or <K,V>
) just before the method's return type.
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.
The method signature you posted looks like this:
public static <T> T getFirst (List<T> list)
And for comparison, here are two close variations:
This method signature isn't a "generic method". Note that this method also removes the static
keyword – it isn't allowed to define method that is static, uses a type parameter (T
), but isn't a generic method.
public T getFirst (List<T> list)
This is a generic method (method type <T>
define just prior to return type T
), but isn't static:
public <T> T getFirst (List<T> list)
Upvotes: 0
Reputation:
T
Means Type parameter in java.lang.Class
, added this type parameter.Its simply say type checking to compiler.
Upvotes: 2
Reputation: 85779
The T
before the method name means that returns a value of type T
, where T is the template used in the method. If your method will return an int
, it would look like:
public static <T> int getFirst (List<T> list)
Upvotes: 4