Reputation: 604
I have seen some code like this and unable to understand its significance:
public class ClassA{
public <T> void getContactName(ContactList<T> contactList){
//do something
}
}
Basically I didn't understand this. The class compiles without any error. I thought ClassA should also be made generic with parameter 'T' .
Thanks
Upvotes: 2
Views: 122
Reputation: 62864
The definition
public <T> void getContactName(ContactList<T> contactList){
//do something
}
means that only the method is generic and the type with a name T
is valid only in the scope of the method. There's no need the class to be generic if the T
type parameter is used only in a single method.
As a side note, remember that in Java you can make generic:
but you can't make generic:
Upvotes: 6
Reputation: 586
According to Java Language Specification:
You can use your method like this:
new ClassA().<String>getContactName(contactList);
or you can not specify the type parameter
new ClassA().getContactName(contactList);
You can read specification for further details and good faq you can find here
Upvotes: 1
Reputation: 46841
It's better explained under Java Tutorial on Generic Methods and Generic Types along with detail examples and uses of generic methods.
here is an example (build-in Arrays
class). Have a look at the method signature that ensures that method return type is exactly same as method arguments since class itself is not generic but you can make method as generic.
class Arrays {
public static <T> List<T> asList(T... a) {
...
}
You can create static generic utility methods
as mentioned above where you don't need to create object
of the class.
Upvotes: 2