What is the use of <T> in public static <T> T addAndReturn(T element, Collection<T> collection){

Jegan Kunniya picture Jegan Kunniya · Nov 3, 2009 · Viewed 26.1k times · Source

I get confused when I come across a generic method of this sort.

public static <T> T addAndReturn(T element, Collection<T> collection){
    collection.add(element);
    return element;
}

I cannot understand why <T> is required in this method.

Also, what is the difference between generic methods and the methods that use generics syntax?

Answer

Samuel Meacham picture Samuel Meacham · Nov 10, 2009
> public static <T> T addAndReturn(T
> element, Collection<T> collection){
>     collection.add(element);
>     return element; }

The <T> (in angle brackets) is known as the generic type parameter, whereas the T directly preceeding the method name is the return type. You might have a generic method that returns some other type than the generic type. Perhaps you want a method that adds an element to a collection (so an object of type T), and rather than returning the added object (which would also be of type T), you want it to return the index of that item in the collection, which would always be an int.

Example method signature where the return type is not the generic type:

public static <T> Integer addAndReturn(T element, Collection<T> collection)

Generic methods, like any other method, can have any return type, including the generic type itself, any other class type, any basic or inherent data type, or void. You may be confusing 2 unrelated parts of the method signature, thinking they are dependent, when they are not. They are only "dependent" in the sense that if you do use T as the return type, the return value's type is of the generic type you provide at the call site.