I wonder why generic methods which return nothing void are (or can be) declared this way:

   public static <E> void printArray( E[] inputArray ) {
     // Display array elements              
     for ( E element : inputArray ){        
        System.out.printf( "%s ", element );
     }
     System.out.println();
   }

It seems like <E> is the type of the returned object, but the method returns nothing in fact. So what is the real meaning of <E> in this case specifically and in generic methods generally?


Solution 1:

This question suits one of my old notes. I hope this illustration helps:

enter image description hereenter image description here

Solution 2:

The <E> is the generic type parameter declaration. It means "this method has a single type parameter, called E, which can be any type".

It's not the return type - that comes after the type parameter declaration, just before the method name. So the return type of the printArray method in your question is still void.

See section 8.4 of the JLS for more details about method declarations.

Solution 3:

It's not the type of the returned object. It indicates that E, in the method signature, is a generic type and not a concrete type. Without it, the compiler would look for a class named E for the argument of the method.