How to create generic method?

It is possible to create generic method withen non generic class.
class demo
void display(T x){System.out.println(x);}
public static void main(String[] args){
demo d=new demo();
d.display(new Integer(10));
Another Example:
Here the isin() is a static generic method.
The isin() demonstrates whether an object is a member of array. It can be used with any type of Object and array as long as the array contains objects that are compatible with the type of the Object being sought.
class demo
static boolean isin(T x,V[] y){
for(int i=0;i if(x.equals(y[i])) return true;
return false;
public static void main(String[] args){
Integer nums[]={1,2,3,4,5,6,7,8,9};
System.out.println("7 is in the array?\t"+isin(7,nums));
System.out.println("10 is in the array?\t"+isin(10,nums));

String names[]={"bhabani","pinku","bbc","samanta"};
System.out.println("bhabani is in the array?\t"+isin("bhabani",names));
System.out.println("mahesh is in the array?\t"+isin("mahesh",names));
Here T is the type parameter. V is upper bounded by T. So V must be subclass of T or same as T.This relation enforces isin() can be called only with arguments that are compatible with eachother. Isin() is static, enabling it to be called independently of any object.

No comments:

Post a Comment