Return Type of Java Generic Methods

2019-01-06 10:27发布

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?

5条回答
闹够了就滚
2楼-- · 2019-01-06 11:06

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

enter image description here enter image description here

查看更多
Rolldiameter
3楼-- · 2019-01-06 11:09

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.

查看更多
再贱就再见
4楼-- · 2019-01-06 11:17

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.

查看更多
Summer. ? 凉城
5楼-- · 2019-01-06 11:28

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).

查看更多
欢心
6楼-- · 2019-01-06 11:30

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

查看更多
登录 后发表回答