简体   繁体   中英

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. 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.

A short explanation on type inference given in the Oracle documentation:

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 . The Oracle tutorial on Generic Methods is also useful, albeit not nearly as extensive as the other references.

1. How compiler know, what is the type of the collection?

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?

Because that's the language's syntax for declaring a generic method. See the JLS § 8.4.4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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