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

27,455

Solution 1

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

Solution 2

The alternative, using object instead of T, would cause the function to return object.

When it returns T, you can do something like:

addAndReturn(myElement, col).SomeMethodOfMyElement();

If addAndReturn returned object instead, you would have to use either

((MyElementType)addAndReturn(myElement, col)).SomeMethodOfMyElement();

which needs an explicit cast, or

addAndReturn(myElement, col);
myElement.SomeMethodOfMyElement;

which needs two statements instead of one.


EDIT: Now that your question has been formatted, I see that one of the parameters is Collection<T>. In that case, the generic syntax ensures that

addAndReturn(mySquare, collectionOfCircles);

returns a compile-time error instead of a run-time error.


EDIT: And just in case your question was about the <T> syntax rather than about the use of generics in general: The <T> tells the compiler that the T used in the method definition is not some class T but rather a placeholder for whatever class "fits" for a specific call of the method.

Share:
27,455
Jegan Kunniya
Author by

Jegan Kunniya

Updated on July 10, 2022

Comments

  • Jegan Kunniya
    Jegan Kunniya almost 2 years

    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?