英文:
What is the difference between "<T> T" and "T" return types in JavaDocs
问题
仍在努力理解泛型,因此需要帮助,将不胜感激。
英文:
Still wrapping my head around generics so help would be appreciated.
答案1
得分: 8
在这两种情况下,返回类型都是 T
。
如果你在之前看到了 <T>
,那么意味着泛型类型 T
已在方法级别进行了定义:
<T extends JustAnExample> T getThatThing() {
// ...
}
如果没有的话,那么可能是在类级别进行了定义:
class MyClass<T extends JustAnExample> {
T getThatThing() {
// ...
}
}
或者,从技术上讲,它也可以只是一个名为 T
的类,尽管这些单个字母的类型通常是指泛型(完全是按照惯例):
class MyClass {
T poorlyNamedTypeYuck() {
// ...
}
}
请注意,你不必将 T
作为返回类型:
<T> void thisIsAlsoValid(T genericUsedHere, List<T> orElseWhere) {
// ...
}
英文:
In both cases, the return type is T
.
If you see <T>
before though, it means that the generic type T
has been defined at the method level:
<T extends JustAnExample> T getThatThing() {
// ...
}
If not, then it has probably been defined at the class level:
class MyClass<T extends JustAnExample> {
T getThatThing() {
// ...
}
}
Or, it can technically also simply be a class named T
, although those single-letter types usually refer to generics (purely by convention):
class MyClass {
T poorlyNamedTypeYuck() {
// ...
}
}
Note that you don't have to use T
as the return type:
<T> void thisIsAlsoValid(T genericUsedHere, List<T> orElseWhere) {
// ...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论