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

南笙酒味 提交于 2021-01-28 11:15:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/60010353/what-does-t-before-the-return-type-of-a-method-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!