为什么需要在JAVA中的void静态方法签名中声明泛型?
Why do you need to declare the generic type in a void static method signature in JAVA?
为什么下面一段代码要编译时必须跟在static后面加上用过的Genericclass?
public static<Integer>void main(String args[]){
BinaryTree<Integer> tree = new BinaryTree<Integer>();
}
我想这可能无法编译的一种方式可能是你有这样的东西
public class Test<Integer> {
public static<Integer> void main(String args []){
Map<Integer, String> aHash = new HashMap<Integer, String>();
}
}
并且您使用 "Integer" 作为类型参数(这是合法的,但可能不是最好的主意)
现在这适用于非静态方法,即
public class Test<Integer> {
public void main(String args []){
Map<Integer, String> aHash = new HashMap<Integer, String>();
}
}
可以正常编译,但对于静态方法,不能使用 class 类型参数,因为您会对非静态类型参数进行静态引用。
我只能假设您正在尝试做的是定义一个 BinaryTree
class,其节点类型为 Integer
,因此您编写了类似这样的内容。
public class BinaryTree<Integer> {
// Code
public static void main(String args[]) {
BinaryTree<Integer> tree = new BinaryTree<Integer>();
}
}
在上面的代码中,Integer
没有它通常的含义。因为它出现在 class 名称后的 angular 括号中,所以它实际上是一个类型参数。通常类型参数具有单字母名称,但名称 Integer
是允许的。
因为main
方法是静态的(属于class,不是class的一个单独实例),它无权访问类型参数。这就是 main
的代码无法编译的原因。
通过写作
publie static <Integer> void main(String args[])
相反,您正在使 main
方法通用。方法的类型参数(再次称为 Integer
!)隐藏了 class 的类型参数,代码编译。
要解决此问题,您可以使 class 具有类型参数 T
,或者完全删除 class 类型参数(如果所有 BinaryTree
实例具有输入 Integer
,根本不需要 class 是通用的。
为什么下面一段代码要编译时必须跟在static后面加上用过的Genericclass?
public static<Integer>void main(String args[]){
BinaryTree<Integer> tree = new BinaryTree<Integer>();
}
我想这可能无法编译的一种方式可能是你有这样的东西
public class Test<Integer> {
public static<Integer> void main(String args []){
Map<Integer, String> aHash = new HashMap<Integer, String>();
}
}
并且您使用 "Integer" 作为类型参数(这是合法的,但可能不是最好的主意)
现在这适用于非静态方法,即
public class Test<Integer> {
public void main(String args []){
Map<Integer, String> aHash = new HashMap<Integer, String>();
}
}
可以正常编译,但对于静态方法,不能使用 class 类型参数,因为您会对非静态类型参数进行静态引用。
我只能假设您正在尝试做的是定义一个 BinaryTree
class,其节点类型为 Integer
,因此您编写了类似这样的内容。
public class BinaryTree<Integer> {
// Code
public static void main(String args[]) {
BinaryTree<Integer> tree = new BinaryTree<Integer>();
}
}
在上面的代码中,Integer
没有它通常的含义。因为它出现在 class 名称后的 angular 括号中,所以它实际上是一个类型参数。通常类型参数具有单字母名称,但名称 Integer
是允许的。
因为main
方法是静态的(属于class,不是class的一个单独实例),它无权访问类型参数。这就是 main
的代码无法编译的原因。
通过写作
publie static <Integer> void main(String args[])
相反,您正在使 main
方法通用。方法的类型参数(再次称为 Integer
!)隐藏了 class 的类型参数,代码编译。
要解决此问题,您可以使 class 具有类型参数 T
,或者完全删除 class 类型参数(如果所有 BinaryTree
实例具有输入 Integer
,根本不需要 class 是通用的。