Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use <T> in generic method's declaration

What is the difference between this:

T getById(Integer id);

And this:

<T> T getById(Integer id);

Are they not both returning a class with type T?

like image 842
Mikael S. Avatar asked Feb 02 '14 14:02

Mikael S.


2 Answers

Yes, but you will have to declare T somewhere. What changes is where you do.

  • In the first case, T is defined at class level, so your method is part of a generic class and you will have to specialize the class when you declare/instantiate. T will be the same for all methods and attributes in the class.
  • In the second, T is defined at method level, so it's a generic method. Value for T can (often) be deduced.

In the first case, the scope of T is the whole class, while in the second is the method only.

The second form is used commonly with static methods. Also, the latter has the advantage that the type variable T can be deduced (you don't have to specify it in most cases), while you have to specify it for the former.

Specifically, you will have to use a generic class if some attributes of it depend on T (are of type T, List<T>, etc.).

like image 144
Stefano Sanfilippo Avatar answered Oct 29 '22 23:10

Stefano Sanfilippo


In the first snippet, T is referring to the type variable declared in the class' type parameter list.

In the second snippet, you are creating a new type variable T (which may shadow the class one), declared in the method parameter list.

like image 42
Sotirios Delimanolis Avatar answered Oct 29 '22 23:10

Sotirios Delimanolis