generics中的wildcard ?
代表unknown type,并且只接受null
.
然而,在下面的示例中,constructor接受(for example)一个String
对象,即使我声明了一个Test<?>
的实例.
public class Test<T> {
private T object;
public Test(T object) {
this.object = object;
}
public void set(T object) {
this.object = object;
}
public static void main(String[] args) {
Test<?> test = new Test<>("Test"); // compiles fine
//test.set("Test"); // compiler error
}
}
为什么这个编译正常?