Source of GenericMethodWithOneParameter.java


  1: //GenericMethodWithOneParameter.java
  2: //You can have a generic method in a non-generic class.
  3: //This program illustrates a generic method used to display
  4: //the values in an array containing values of any type.

  6: public class GenericMethodWithOneParameter
  7: {
  8:     //A generic method to display the values in any array
  9:     public static <T> void printArray(T[] inputArray)
 10:     {
 11:         //Display array elements
 12:         for (T element : inputArray)
 13:         {
 14:             System.out.printf("%s ", element);
 15:         }
 16:         System.out.println();
 17:     }

 19:     public static void main(String[] args)
 20:     {
 21:         System.out.println();

 23:         //Create arrays of Integer, Double and Character
 24:         Integer[] intArray =
 25:         {
 26:             1, 2, 3, 4, 5
 27:         };
 28:         Double[] doubleArray =
 29:         {
 30:             1.1, 2.2, 3.3, 4.4
 31:         };
 32:         Character[] charArray =
 33:         {
 34:             'H', 'E', 'L', 'L', 'O'
 35:         };

 37:         //Now display those arrays using the generic method
 38:         System.out.println("Array integerArray contains:");
 39:         printArray(intArray);
 40:         System.out.println("\nArray doubleArray contains:");
 41:         printArray(doubleArray);
 42:         System.out.println("\nArray characterArray contains:");
 43:         printArray(charArray);
 44:     }
 45: }