< T& gt;方法的返回类型之前是什么意思? [英] What does <T> before the return type of a method mean?

查看:50
本文介绍了< T& gt;方法的返回类型之前是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下方法返回由 T 类型元素组成的List:

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

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

在签名中,我们有< T>列出< T> . List< T> 是有意义的,因为那是返回值的类型.但是,前面的< 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?

在没有< T> List< T> 的情况下,代码无法编译.省略< T> 给出

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

无法解析符号T

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.

推荐答案

第一个< T> 表示第二个 T 是通用参数的占位符,不是要在该列表中存储的类的实际名称.

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.

没有第一个< T> 编译器会将 T 视为类名(例如 Object String 等),尝试在与使用该方法的类相同的包中或在使用该方法的类的import部分中找到名为 T 的类.如果编译器无法找到名为 T 的类,则会显示编译错误.

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.

这篇关于&lt; T&amp; gt;方法的返回类型之前是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆