1.

Can You Give An Example Of A Generic Method?

Answer»

A generic type can be declared as part of method declaration as well. Then the generic type can be used anywhere in the method (return type, parameter type, LOCAL or block variable type).

Consider the method below:

static <X extends Number&GT; X doSomething(X number){
X result = number;
//do something with result
return result;
}
The method can now be called with any Class type EXTEND Number.




Integer i = 5;
Integer K = doSomething(i);

A generic type can be declared as part of method declaration as well. Then the generic type can be used anywhere in the method (return type, parameter type, local or block variable type).

Consider the method below:

static <X extends Number> X doSomething(X number){
X result = number;
//do something with result
return result;
}
The method can now be called with any Class type extend Number.




Integer i = 5;
Integer k = doSomething(i);



Discussion

No Comment Found