小编Gio*_*gos的帖子

Why does an instance of Test<?> accept non-null objects in the constructor?

The wildcard ? in generics represents an unknown type and accepts only null. However, in the following example, the constructor accepts (for example) a String object, even though I have declared an instance of 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
    } …
Run Code Online (Sandbox Code Playgroud)

java generics wildcard

0
推荐指数
1
解决办法
41
查看次数

标签 统计

generics ×1

java ×1

wildcard ×1