When to use <T> in a generic method declaration
Yes, but you will have to declare T somewhere. What changes are you making.
- In the first case,
Tis defined at the class level, so your method is part of a generic class, and you will have to specialize the class when declaring / creating an instance.Twill be the same for all methods and attributes in the class. - In the second,
Tis defined at the method level, so this is a general method. The value forTcan (often) be output.
In the first case, the domain T is the whole class, and in the second, only the method.
The second form is usually used with static methods. In addition, the latter has the advantage that a variable of type T can be inferred (you do not need to specify it in most cases), while you must specify it for the former.
In particular, you will have to use a common class if some of its attributes are dependent on T (they are of type T , List<T> , etc.).
The first returns the type T of the enclosing type type. For instance,
T get(int index); declared in the class List<T> , returns an element of type T at the specified index List<T> .
The second one declares that the method itself is a universal method whose return type depends on how it is called. If you call it like
String s = theObject.<String>getById(id); it will return a string. If you call it like
Foo f = theObject.<Foo>getById(id); he will return foo. In most cases, the generic type is inferred automatically by the compiler, so you can simply write
Foo f = theObject.getById(id); For a specific example, see
static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) which returns the maximum element of type T in the collection T. The type returned by the method depends on the type of collection passed to the method.