javagenericsgeneric-programminggeneric-methodgeneric-type-argument

Why i am getting error by setting the Integer type parameter to the Integer variable in generics?


I have the following program:

class MyGenClass{

    public <T> void setAge(T ageParam){
        Integer age = ageParam;
    }

}
class Program{

    public static void main(String args[]){

        MyGenClass gnClass = new MyGenClass();
        gnClass.<Integer>setAge(80);

    }

}

In fact, i am passing the Integer then why the ageParam is not assigned to age. And when i do:

class MyGenClass{

    public <T> void setAge(T ageParam){
        T age = ageParam;
    }

}

Why the generic type variable is not assigned to the Integer type variable age in fact the generic type variable ageParam is Integer. Is this compulsory that the ageParam must be assigned to the variable that is of type T? Whats the scenario behind this?


Solution

  • There is not assured that the type T will be compatible with Integer. To make it clear, you have to use the following approach where T would be a subtype of Integer:

    public <T extends Integer> void setAge(T ageParam){
        age = ageParam;
    }
    

    However, I see no point on this. Consider the following approach for the sake of variability:

    class MyGenClass {
        Number age;
        public <T extends Number> void setAge(T ageParam){
            age = ageParam;
        }
    }
    

    Therefore the following is possible (the explicit type arguments can be inferred, thought):

    MyGenClass gnClass = new MyGenClass();
    gnClass.<Integer>setAge(80);
    gnClass.<Long>setAge(80L);
    gnClass.<Double>setAge(80.0);
    gnClass.<Float>setAge(80.0F);