Friday, November 2, 2012

Java Generic Method

Here is an example of Java's generic method


package com.giri.test;

public class GenericMethodTest {

 public static  void printArray(E[] inputArray) {
  for(E element : inputArray ) {
   System.out.printf(" %s ", element);
  }
  
  System.out.println("\n");
 }
 
 public static void main(String[] args) {
  Integer[] integerArray = { 1, 2, 3, 4, 5 };
  Double[] doubleArray = { 1.11, 2.55, 3.66, 4.99, 10.1101 };
  Character[] charArray = { 'J', 'A', 'V', 'A', ' ', 'I', 'S', ' ', 'C', 'O', 'O', 'L' };
  
  System.out.println("Array integerArray contains: ");
  printArray(integerArray);
  
  System.out.println("Array doubleArray contains: ");
  printArray(doubleArray);
  
  System.out.println("Array charArray contains: ");
  printArray(charArray);
 }

}

Output:


Array integerArray contains: 
 1  2  3  4  5 

Array doubleArray contains: 
 1.11  2.55  3.66  4.99  10.1101 

Array charArray contains: 
 J  A  V  A     I  S     C  O  O  L 

Following example illustrate how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). This example is Generic method to return the largest of three Comparable objects

package com.giri.test;

public class CompareTest {

 public static > T maximum(T x, T y) {
  T ret = null;
  if(x.compareTo(y) > 0) {
   ret = x;
  } else {
   ret = y;
  }
  return ret;
 }
 
 public static void main(String[] args) {
  int i_x =  5;
  int i_y = 50;
  
  double d_x =  1.35363;
  double d_y = 10.33636;
  
  String s_x = "Apple";
  String s_y = "Zebra";
  
  System.out.printf("\nInteger: Maximum of %d and %d is: %d \n\n", i_x,i_y, maximum(i_x,i_y));
  
  System.out.printf("\nDouble: Maximum of %.5f and %.5f is: %.5f \n\n", d_x,d_y, maximum(d_x,d_y));
  
  System.out.printf("\nString: Maximum of %s and %s is: %s \n\n", s_x,s_y, maximum(s_x,s_y));
 }

}

Output:

Integer: Maximum of 5 and 50 is: 50 


Double: Maximum of 1.35363 and 10.33636 is: 10.33636 


String: Maximum of Apple and Zebra is: Zebra 

No comments :

Post a Comment