Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between <T> T vs T in the return type of a method?

Tags:

java

generics

I have a method, like this,

public <T> T doSomething(Class<T> T) {
return T.newInstance();
}

I can also do the same like this,

public T doSomething(Class<T> T) {
return T.newInstance();
}

Is there any difference between these two? Please ignore T.newInstance(), I'm basically going to create a new instance of T somehow and return it.

thanks, sam

like image 369
user3124204 Avatar asked Dec 20 '13 22:12

user3124204


People also ask

What is T in method?

In the first case, T is defined at class level, so your method is part of a generic class and you will have to specialize the class when you declare/instantiate. T will be the same for all methods and attributes in the class. In the second, T is defined at method level, so it's a generic method.

What is the meaning of T T in Java?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.

What is the return type of get method?

The getReturnType() method of Method class Every Method has a return type whether it is void, int, double, string or any other datatype. The getReturnType() method of Method class returns a Class object that represent the return type, declared in method at time of creating the method.


1 Answers

What's the difference between <T> T vs T in the return type of a method?

There is no <T> T. The <T> is not part of the return type; it's a separate thing, indicating the type parameter. (You can also have public <T> void ....)

In the version with <T>, you're declaring T as a type parameter of the method, and the T in the argument and the return-type are referring to that type parameter.

In the version without <T>, you're not declaring T as a type parameter of the method, so it's most likely a type parameter of the containing class or another containing scope. (Alternatively, someone may have named an actual class or interface T, in which case you should give that person a talking-to.)

If both versions compile, then the second is probably the one you want: you probably want to be using the class's type parameter T, rather than adding a new one that hides it. (And if you really do want a new type parameter unrelated to your class's type parameter, then you should use a new name for it to avoid confusion.)

like image 120
ruakh Avatar answered Nov 15 '22 00:11

ruakh