开发者

what this method return?

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 to T)
  • it takes a List<T> as its argument (i.e. a List 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. a List of objects of the concrete type T)
  • 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜