Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic at return type

Tags:

java

generics

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

like image 739
Amit Avatar asked Mar 17 '26 15:03

Amit


2 Answers

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:

  • classes (except the anonymous ones)
  • methods
  • interfaces

but you can't make generic:

  • exceptions
  • anonymous classes
  • enums
like image 106
Konstantin Yovkov Avatar answered Mar 19 '26 13:03

Konstantin Yovkov


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.

like image 33
Braj Avatar answered Mar 19 '26 14:03

Braj