简体   繁体   English

通用方法 - 语法混淆

[英]Generic method - syntax confusion

I am reading about generic methods. 我正在阅读有关通用方法的内容 I have studied that, if you are not declaring the type at the class level and using generic methods, the syntax would be somehow like this 我已经研究过,如果你没有在类级别声明类型并使用泛型方法,语法将会以某种方式像这样

public <T> void makeArrayList(T t)

Here i can conclude following point,If i don't declare the place-holder before the return type, it gives me compile time error. 在这里我可以得出以下结论,如果我没有在返回类型之前声明占位符,它会给我编译时错误。 I am pretty confused. 我很困惑。 I am looking into other topics Java Generics: Generic type defined as return type only but it seems quite confusing. 我正在研究Java Generics的其他主题:通用类型仅定义为返回类型,但它似乎很混乱。 My question is 我的问题是

  1. How compiler know, what is the type of the collection? 编译器如何知道,集合的类型是什么?
  2. Why do we need to declare the type before return-type? 为什么我们需要在返回类型之前声明类型?

Can someone elaborate on this point? 有人可以详细阐述这一点吗?

If you don't put the <T> in the header, the function has no way of knowing that T exists. 如果未将<T>放在标题中,则该函数无法知道T存在。

A short explanation on type inference given in the Oracle documentation: 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. 它通常会推断出使调用类型更正的最具体的类型参数。

References: 参考文献:
I highly recommend reading Java Generics FAQ , in particular, the section on Java Generic Methods . 我强烈建议阅读Java Generics FAQ ,特别是关于Java Generic Methods的部分。 The Oracle tutorial on Generic Methods is also useful, albeit not nearly as extensive as the other references. 关于通用方法Oracle教程也很有用,尽管不像其他参考文献那样广泛。

1. How compiler know, what is the type of the collection? 1.编译器如何知道,集合的类型是什么?

The type is whatever type you pass in at each method call. 类型是您在每次方法调用时传递的任何类型。 There is no concrete type in the method's declaration; 方法声明中没有具体的类型; that's what it means to declare a generic method. 这就是声明泛型方法的意思。

2. Why do we need to declare the type before return-type? 2.为什么我们需要在return-type之前声明类型?

Because that's the language's syntax for declaring a generic method. 因为这是声明泛型方法的语言语法。 See the JLS § 8.4.4. 参见JLS§8.4.4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM