When to use <T> in a generic method declaration

What is the difference between this:

T getById(Integer id); 

And this:

 <T> T getById(Integer id); 

They do not return a class with type T ?

+6
source share
4 answers

Yes, but you will have to declare T somewhere. What changes are you making.

  • In the first case, T is 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. T will be the same for all methods and attributes in the class.
  • In the second, T is defined at the method level, so this is a general method. The value for T can (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.).

+6
source

In the first fragment, T refers to a type variable declared in the list of class type parameters.

In the second fragment, you create a new variable of type T (which can obscure the class), declared in the method parameter list.

+8
source

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.

+5
source

Other answers explain well when used, I provide an example

For point 1

 class ArrayList<E> {//implementing and extending public E get(int index) { } } 

For point 2: static utility method

 public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); } 
+2
source

All Articles