Intro to generic methods

  • Consider this program that contains the overloaded method print( ):

       public static void main(String[] args)
       {
           String[]  strings  = {"a", "b", "c"};
           Integer[] integers = {1, 2, 3, 4, 5};
    
           print( strings );  // Calls print(String[])
           print( integers ); // Calls print(Integer[])
       }
    
       public static void print(String[] list)
       {
           for ( int i = 0; i < list.length; i++ )
               System.out.println(list[i]);
       }
    
       public static void print(Integer[] list)
       {
           for ( int i = 0; i < list.length; i++ )
               System.out.println(list[i]);
       }
    

  • We can use generic (= parameterized) methods to avoid having to write 2 similar methods

DEMO: demo/06-generics/03-gen-method/Demo.java

Defining generic methods

  • Syntax to define a generic (parameterized) method:

       public static <T1,T2,..> returnType methodName( params )
       {
           ...
       }

    You can use the type parameters T1, T2, ... to declare parameter variables, local variables and the return type of the method

  • Example of a generic (parameterized) method definition:

       public static <T> void print( T[] list )
       {
           for ( int i = 0; i < list.length; i++ )
               System.out.println(list[i]);
       }

    The generic method will be made specific (with a data type) in the invocation.

What happens behind the scene when you define a generic method

  • When you write the following generic method:

       public static <T> void print( T[] list )
       {
           for ( int i = 0; i < list.length; i++ )
               System.out.println(list[i]);
       }

    The Java compiler will replace every occurence of <T> by Object:

       public static void print( Object[] list )
       {
           for ( int i = 0; i < list.length; i++ )
               System.out.println( list[i] );
       }

    and will remember that list[ ] is a parameterized class variable

  • When the print( ) method is used, the Java compiler will insert the appropriate casting operator (see next slide)

Invoking generic methods

  • Syntax to invoke a generic (parameterized) method:

       ClassName.<T1,T2,..>methodName( arguments ) 

  • Examples of a generic (parameterized) method invocations:

     String[]  strings  = {"a", "b", "c"};
     Integer[] integers = {1, 2, 3, 4, 5};
    
     Demo2.<String>print( strings );   // Inserts (String) cast operator
     Demo2.<Integer>print( integers ); // Inserts (Integer) cast operator 

  • Alternate syntax: (because Java can imply the data type)

     Demo3.print( strings );   
     Demo3.print( integers );  

DEMO: demo/06-generics/03-gen-method/Demo2.java + Demo3.java

More on generic methods later

  • We will discuss sorting later in the course

  • The sorting algorithm will written as generic methods

    So we will see more examples of generic method later