javagenericsgeneric-method

What does <T> before the return type of a method mean?


The following method returns a List composed of T type elements:

public <T> List<T> getList() {
    return new ArrayList<T>();
}

In the signature we have <T> List<T>. The List<T> makes sense, because that is the type of the return value. What is the need for the preceding <T> though?

The code doesn't compile without both <T> and List<T>. Leaving out the <T> gives

Cannot resolve symbol T


I have read the official Oracle tutorial on generic methods. It explains that this is part of the syntax:

The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

But it does not really explain why it is needed in the first place or what exact effect it has on the method.


Solution

  • The first <T> signifies that the second T is a placeholder for a generic parameter and not the actual name of class which you are going to store in that list.

    Without that first <T> compiler will treat T as a class name (like Object, String, etc) try to find a class named T in the same package where the class with that method exists or in the import section of the class with that method. And if compiler is unable to find class named T it will show compilation error.