我正在阅读泛型方法。我研究过,如果您不在类级别声明类型并使用泛型方法,则语法会以某种方式像这样
public <T> void makeArrayList(T t)
在这里我可以得出以下结论,如果我不在返回类型之前声明占位符,它会给我编译时错误。我很困惑。我正在研究其他主题 Java Generics: Generic type defined as return type only但它似乎很困惑。我的问题是
- 编译器如何知道集合的类型是什么?
- 为什么我们需要在返回类型之前声明类型?
有人可以详细说明这一点吗?
最佳答案
如果你不把 <T>
在 header 中,函数无法知道 T
存在。
Oracle 文档中对类型推断的简短解释:
The compiler infers the type argument for us, based on the types of the actual arguments. It will generally infer the most specific type argument that will make the call type-correct.
引用资料:
我强烈推荐阅读 Java Generics FAQ ,特别是关于 Java Generic Methods 的部分. Oracle tutorial on Generic Methods也很有用,尽管不如其他引用资料广泛。
关于java - 泛型方法——语法困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18176250/