Friday, 15 August 2014

Generic method




In method overloading, name of the method remain same but with different parameter and method is bounded to handle call with limited type of parameters. One more loophole is that method needs to declare and define for every different type of parameter.

Example :- 

public void show(string s){}
public void show(int s){}
public void show(long s){}
public void show(char s){}

To overcome this problem, generic method comes to the front. In generic method there is no need to define method again and again. Only once it is defined and works for all.

public static void main(String[] args) {
Integer [] arr={1,2,3,4,5,6};
String []str={"str1","str2","str3","str4"};

   Long [] lArr={232l,23231l,564445l};

// call with string array.
getVal(str,"call with String");

  // call with Integer array.
getVal(arr,"call with Integer");

   //call with Long Array
   getVal(lArr, "call with Long");
}

//generic method getVal.
 public static <T,EE> T[] getVal(T [] x, EE e)
{
          if(x instanceof Integer[])
 System.out.println(e);
   else
 System.out.println(e);

for(T val:x){
System.out.print(val+", ");
}
System.out.println("\n");
return x;
}




Output :>


No comments:

Post a Comment