Java generics - Why is this assignment in the constructor illegal?

Tom Joe :

Why do I get a compiler error in this code ? How do I fix it ?

public class Container<T> {
    private T content;
    private T defaultValue;

    public <T> Container(T defaultValue){
        //Compiler error - incompatible types: T cannot be converted to T.
        this.defaultValue = defaultValue;
    }
}

After type erasure, T defaultValue would become Object defaultValue. Then why can't we assign T defaultValue to Object defaultValue ? After all, every type in Java is an Object.

Spidy :

Remove the <T> from in front of the constructor. Java thinks you are trying to create a new generic. It thinks the T you have in the class statement is a different T then you have in the constructor. In Java's eyes you have T1 and T2. You are trying to assign T2 to a T1 variables. Even though they may be identical in methods, inheritance, etc... they are two distinct generics.

This is how Java interprets what you've written.

public class Container<T1> {
    private T1 content;
    private T1 defaultValue;

    public <T2> Container(T2 defaultValue){
        //Compiler error - incompatible types: T cannot be converted to T.
        this.defaultValue = defaultValue;
    }
}

What you meant to write was this. You don't need to specify T inside < > anywhere since it's included in the class syntax.

public class Container<T> {
    private T content;
    private T defaultValue;

    public Container(T defaultValue){
        this.defaultValue = defaultValue;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=477965&siteId=1