为什么在通用类(Java)的构造函数中提供类型参数是错误的? [英] Why is it wrong to supply type parameter in the constructor of a generic class (Java)?
问题描述
我只是从一本教科书中学习Java中的泛型,其中谈到用 ArrayList实现的类
。 GenericStack< E>
E>
I'm just learning about generics in Java from a textbook, where it talks about a class GenericStack<E>
implemented with an ArrayList<E>
.
由于为了创建一个字符串堆栈,您使用
Since in order to create a stack of strings, you use
GenericStack<String> = new GenericStack<String>()
或
GenericStack<String> new GenericStack<>()
因此不应该使用
GenericStack
定义为 public GenericStack< E>()
或 public GenericStack& / code>?答案是不。它应该定义为
public GenericStack()
。
therefore shouldn't the constructor of
GenericStack
be defined as public GenericStack<E>()
, or public GenericStack<>()
? The answer is no. It should be defined as public GenericStack()
.
为什么?显然,构造函数可以很容易地从类声明推断类型,但考虑到Java的冗长,我有点糊涂为什么< E>
Why is this? Obviously the constructor can easily infer the type from the class declaration, but given the verbosity of Java, I'm a bit befuddled why the <E>
or simply the <>
formalism is completely gotten rid of here.
推荐答案
这里有这两个部分:
-
为类定义提供的泛型类型参数在类本身内可用。
The generic type parameter given for the class definition is available within the class itself.
您可以为个别方法(包括构造函数)指定通用类型。
You can have generic types specific to individual methods (including constructor).
查看以下示例:
package snippet;
import java.util.ArrayList;
public class Y<E> extends ArrayList<E> {
public <T> Y(T t) {
}
}
code> E 可用于整个类,类型 T
仅在构造函数中有效。
Where as the type E
is available to the whole of the class, the type T
is valid only within the constructor.
这篇关于为什么在通用类(Java)的构造函数中提供类型参数是错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!