Using generic methods to print array of different types : Generic Method « Generics « Java Tutorial






public class MainClass {
  // generic method printArray
  public static <E> void printArray(E[] inputArray) {
    // display array elements
    for (E element : inputArray)
      System.out.printf("%s ", element);

    System.out.println();
  }

  public static void main(String args[]) {
    // create arrays of Integer, Double and Character
    Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
    Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
    Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };

    System.out.println("Array integerArray contains:");
    printArray(integerArray); // pass an Integer array
    System.out.println("\nArray doubleArray contains:");
    printArray(doubleArray); // pass a Double array
    System.out.println("\nArray characterArray contains:");
    printArray(characterArray); // pass a Character array
  } // end main
}
Array integerArray contains:
1 2 3 4 5 6 

Array doubleArray contains:
1.1 2.2 3.3 4.4 5.5 6.6 7.7 

Array characterArray contains:
H E L L O








12.3.Generic Method
12.3.1.Creating a Generic Method
12.3.2.Generic Constructors
12.3.3.Generic methods: Max. Min
12.3.4.Generic method maximum returns the largest of three objects
12.3.5.Using generic methods to print array of different types
12.3.6.Wildcard test program