Generic method maximum returns the largest of three objects : Generic Method « Generics « Java Tutorial






public class MainClass {
  // determines the largest of three Comparable objects
  public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
    T max = x; // assume x is initially the largest

    if (y.compareTo(max) > 0)
      max = y; // y is the largest so far

    if (z.compareTo(max) > 0)
      max = z; // z is the largest

    return max; // returns the largest object
  } // end method maximum

  public static void main(String args[]) {
    System.out.printf("Maximum of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5));
    System.out.printf("Maximum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6,
        8.8, 7.7));
    System.out.printf("Maximum of %s, %s and %s is %s\n", "pear", "apple", "orange", maximum(
        "pear", "apple", "orange"));
  }
}
Maximum of 3, 4 and 5 is 5

Maximum of 6.6, 8.8 and 7.7 is 8.8

Maximum of pear, apple and orange is pear








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