I am reading the following code,
public static <t> T getFirst(List&l开发者_JS百科t;T> list)
I understand the List<T> list
, the method get a reference to List<T>
as parameter, and return
an object with type T
, but what about the <t>
after the keyword public static?
what does this mean?
<t>
declares a type parameter. That means that the method has a type parameter that can change on each invocation.
Unless T
is a concrete type in your project (which is unlikely), the <t>
should be <T>
.
So in plain english <T> T getFirst(List<T> list)
means:
- there's a method called
getFirst
- it has a type parameter
T
(i.e. an arbitrary type which is aliased toT
) - it takes a
List<T>
as its argument (i.e. aList
of objects of that arbitrary type). - it returns a
T
object (i.e. an instance of that arbitrary type).
If you just wrote T getFirst(List<T> list)
then the meaning would change:
- there's a method called
getFirst
- it takes a
List<T>
as its argument (i.e. aList
of objects of the concrete typeT
) - it returns an object of the concrete type
T
.
It tells the compiler that T
is not any concrete class but a placeholder for a class. Otherwise the compiler would think that List<T>
is a list with elements of type T
. I.e. it marks your method generic
精彩评论