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
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With