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

generics, java, methods

Solution

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.).

Problem

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`?

Original source