Java – what is the difference between T and T in the return type of a method?
I have a way, like this,
public <T> T doSomething(Class<T> T) { return T.newInstance(); }
I can do it like this,
public T doSomething(Class<T> T) { return T.newInstance(); }
What's the difference between the two? Please ignore t.newinstance (). I basically want to create a new instance of T and return it in some way
Thank you, Sam
Solution
No < T > T. < T > is not a return type; It is a separate thing that represents a type parameter (you can also publish < T > void...)
In the version with < T >, you declare t as the type parameter of the method, and the T and return type in the parameter refer to the type parameter
In versions without < T >, you do not declare t as a type parameter of a method, so it is likely to be a type parameter of a containing class or another type parameter of a containing range (or, someone may have named an actual class or interface T, in which case you should speak to that person.)
If both versions are compiled, the second version may be the version you want: you may want to use the type parameter t of the class instead of adding a new version that hides it If you really want a new type parameter independent of the type parameter of your class, you should use a new name to avoid confusion