Java Generics : Syntax Explanation

前端 未结 3 1508
遇见更好的自我
遇见更好的自我 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 <E> 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.<Integer>printArray( intArray  ); // pass an Integer array
    
            System.out.println( "\nArray doubleArray contains:" );
            GenericMethodTest.<Double>printArray( doubleArray ); // pass a Double array
    
            System.out.println( "\nArray characterArray contains:" );
            GenericMethodTest.<Character>printArray( charArray ); // pass a Character array
        } 
    }
    

    So what the <E> 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.

    0 讨论(0)
  • 2021-01-14 21:46

    By <E> you define a generic variable type, if you will write

    public static void printArray( E[] inputArray )
    

    Java will try to find a class with name E, because you don't define E as a generic. The return value in both cases are null, this <E> generic definition part in not a part of return value, it's a separate block of function signature.

    0 讨论(0)
  • 2021-01-14 21:47

    In public static < E > void printArray( E[] inputArray ), the E is just used to signify a Generic parameter. The return type of the method is still void.

    0 讨论(0)
提交回复
热议问题