我一直在尝试使用 Generic,很快我就遇到了一些我无法解释的事情。
例如:
import java.util.*;
public class Main {
public static void main(String[] args) {
//We cannot create List<?> l = new ArrayList<?>();
List<?> l = MagicClass.factory();
}
static class MagicClass {
public static <T> List<T> factory() {
return new ArrayList<T>();
}
}
}
我不明白<T>
可以是显式类型参数,而这个
<?>
未定义。
最佳答案
使用通配符实例化泛型会产生编译错误,因为通配符表示任何类型,而实例化的 ArrayList
应该有一个具体的类型。通配符可用于变量或参数类型,但不能用于创建泛型类型的实例。
this tutorial page 中也提到了这一点:
In generic code, the question mark (
?
), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
另一方面,在factory
方法,T
是将由编译器推断的类型参数,并且由于 List<?>
表示任何类型,它被编译器接受。
关于java - 通用方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27877584/