Java Generics : Syntax Explanation

前端 未结 3 1511
遇见更好的自我
遇见更好的自我 2021-01-14 20:54

I am new to java generics my question is :

public static < E > void printArray( E[] inputArray )

In the above statement when the retu

3条回答
  •  醉梦人生
    2021-01-14 21:43

    The here has nothing to do with the return type; it means that this is a generic function which can take various types of arrays. To be easier to understand, the code could be something like this:

    public class GenericMethodTest
    {
       // 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[] intArray = { 1, 2, 3, 4, 5 };
            Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
            Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
    
            System.out.println( "Array integerArray contains:" );
            GenericMethodTest.printArray( intArray  ); // pass an Integer array
    
            System.out.println( "\nArray doubleArray contains:" );
            GenericMethodTest.printArray( doubleArray ); // pass a Double array
    
            System.out.println( "\nArray characterArray contains:" );
            GenericMethodTest.printArray( charArray ); // pass a Character array
        } 
    }
    

    So what the does it tell the function "There is a generic type E and you accept arrays of E, so if for example I call you with the generic type Integer you accept Integer[]."

    It does not change the return type though. Just like public static doesn't change the return type.

提交回复
热议问题