Generic Method Example - maxGeneric()

This section provides a tutorial example of generic method, maxGeneric(), that shows type compatibility mistakes are detected at the compilation time.

To finish the comparison, I wrote the following tutorial example to implement and test the generic method:

/* MaxGenericMethod.java
 - Copyright (c) 2014, HerongYang.com, All Rights Reserved.
 */
class MaxGenericMethod {
   public static <T extends Comparable<T>> T maxGeneric(T a, T b) {
      if (a.compareTo(b)>=0) {
         return a;
      } else {
      	 return b;
      }
   }
   public static void main(String[] a) {
      String max = MaxGenericMethod.<String>maxGeneric(
         new String("1234"), new String("789"));
      System.out.println("Maximum: "+max);

      // Mistake 1: Runtime exception when calling compareTo()
      // String max1 = MaxGenericMethod.<String>maxGeneric(
      //    new String("1234"), new Integer("789"));

      // Mistake 2: Runtime exception when casting return value
      // Integer max2 = MaxGenericMethod.<String>maxGeneric(
      //    new String("1234"), new String("789")); 
   }
}

If you compile and run this tutorial example, you will get:

C:\herong>javac MaxGenericMethod.java

C:\herong>java MaxGenericMethod

Maximum: 789

The output confirms that my generic method is working!

Now if you uncomment the first and second mistakes and compile the program again with JDK 1.8:

C:\herong>javac MaxGenericMethod.java

MaxGenericMethod.java:19: error: incompatible types: Integer cannot be
   converted to String
         new String("1234"), new Integer("789"));
                             ^
MaxGenericMethod.java:22: error: incompatible types: String cannot be 
   converted to Integer
      Integer max2 = MaxGenericMethod.<String>maxGeneric(
                                                        ^
Note: Some messages have been simplified; recompile with 
   -Xdiags:verbose to get full output
2 errors

If you compile the program again with JDK 1.8 with the suggested option "-Xdiags:verbose", you will get more detailed error messages:

C:\herong>javac.exe" -Xdiags:verbose MaxGenericMethod.java

MaxGenericMethod.java:18: error: method maxGeneric in class 
   MaxGenericMethod cannot be applied to given types;
      String max1 = MaxGenericMethod.<String>maxGeneric(
                                    ^
  required: T,T
  found: String,Integer
  reason: argument mismatch; Integer cannot be converted to String
  where T is a type-variable:
    T extends Comparable<T> declared in method <T>maxGeneric(T,T)
MaxGenericMethod.java:22: error: incompatible types: String cannot be
   converted to Integer
      Integer max2 = MaxGenericMethod.<String>maxGeneric(
                                                        ^
2 errors

The output confirms that the compiler did a good job to catch both type compatibility mistakes!

Note that if you are using the JDK 1.7 compiler, you will get same errors. But the error messages are different:

C:\herong\java_20080000\cod>"\Program Files\java\jdk1.7.0_45\bin\javac.exe" MaxG
enericMethod.java

MaxGenericMethod.java:18: error: method maxGeneric in class 
   MaxGenericMethod cannot be applied to given types;
      String max1 = MaxGenericMethod.<String>maxGeneric(
                                    ^
  required: T,T
  found: String,Integer
  reason: actual argument Integer cannot be converted to String by 
     method invocation conversion
  where T is a type-variable:
    T extends Comparable<T> declared in method <T>maxGeneric(T,T)

MaxGenericMethod.java:22: error: incompatible types
      Integer max2 = MaxGenericMethod.<String>maxGeneric(
                                                        ^
  required: Integer
  found:    String
2 errors

Last update: 2014.

Table of Contents

 About This Book

 Installing JDK 1.8 on Windows

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

Generic Methods and Type Inference

 What Is a Generic Method?

 Comparing Generic Method with Non-Generic Method

 Non-Generic Method Example - maxNonGeneric()

Generic Method Example - maxGeneric()

 Generic Methods in java.util.Collections Class

 Testing Generic Methods in Collections Class

 What Is Type Argument Inference?

 Type Argument Inference by Parameter List

 Type Argument Inference by Return Value

 Generic Methods using Parameterized Types

 Parameterized Type as Generic Method Return Type

 Lambda Expressions and Method References

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Outdated Tutorials

 References

 PDF Printing Version