Generic method - syntax confusion

generics, java

Solution

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.

Problem

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 - How compiler know, what is the type of the collection? - Why do we need to declare the type before return-type? Can someone elaborate on this point?

Original source

Related problems