java Java泛型方法的返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11377248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return Type of Java Generic Methods
提问by Jops
I wonder why generic methods which return nothing void
are (or can be) declared this way:
我想知道为什么不返回任何内容的泛型方法void
(或可以)以这种方式声明:
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?
看起来像是<E>
返回对象的类型,但实际上该方法没有返回任何内容。那么<E>
在这种情况下具体和一般方法中的真正含义是什么?
回答by Jops
This question suits one of my old notes. I hope this illustration helps:
这个问题适合我的一个旧笔记。我希望这个插图有帮助:
回答by Jon Skeet
The <E>
is the generic type parameter declaration. It means "this method has a single type parameter, called E
, which can be any type".
该<E>
是泛型类型参数声明。这意味着“此方法具有单个类型参数,称为E
,可以是任何类型”。
It's not the return type - that comes afterthe type parameter declaration, just before the method name. So the return type of the printArray
method in your question is still void
.
这不是返回类型-随附后的类型参数声明,只是方法名之前。所以printArray
你问题中方法的返回类型仍然是void
.
See section 8.4 of the JLSfor more details about method declarations.
有关方法声明的更多详细信息,请参阅JLS 的第 8.4 节。
回答by JB Nizet
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.
它不是返回对象的类型。它表明E
,在方法签名中,是泛型类型而不是具体类型。没有它,编译器会寻找一个以E
方法参数命名的类。
回答by Razvan
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 > 被称为形式类型参数。它不是方法的返回类型。它基本上是说该方法可以接受不同类型的参数数组(E [] inputArray)。
回答by Imran Tufail
Eis used as a placeholder for the actual type that will be passed to Gen function when this function will call.
E用作实际类型的占位符,该类型将在调用此函数时传递给 Gen 函数。
suppose Ecan be replaced by integer
假设E可以用整数代替