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?
This question suits one of my old notes. I hope this illustration helps:
The
<E>
is the generic type parameter declaration. It means "this method has a single type parameter, calledE
, 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 stillvoid
.See section 8.4 of the JLS for more details about method declarations.
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 namedE
for the argument of the method.The < E > is called a formal type parameter. It is not the return type of the method. It basically says that the method can accept as parameters arrays of different types (E[] inputArray).
E is used as a placeholder for the actual type that will be passed to Gen function when this function will call.
suppose E can be replaced by integer