[英]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
. 实际上,我通过了
Integer
然后为什么不将ageParam
分配给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
. 为什么泛型类型变量没有分配给
Integer
类型变量age
实际上,泛型类型变量ageParam
是Integer
。 Is this compulsory that the ageParam
must be assigned to the variable that is of type T
? 是否必须将
ageParam
分配给类型T
的变量? Whats the scenario behind this? 这背后的情况是什么?
There is not assured that the type T
will be compatible with Integer
. 无法保证类型
T
将与Integer
兼容。 To make it clear, you have to use the following approach where T
would be a subtype of Integer
: 为了清楚起见,您必须使用以下方法,其中
T
将是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);
Look at your MyGenClass
in isolation. 孤立地查看您的
MyGenClass
。 T
could be literally anything. T
实际上可以是任何东西。 It is not necessarily an Integer. 它不一定是整数。 I could call it with a String, or a HashMap or an ArrayList, or literally anything else .
我可以用String,HashMap或ArrayList或其他任何名称来调用它。
MyGenClass gnClass = new MyGenClass();
gnClass.setAge("hello");
gnClass.setAge(new HashMap<String, String>());
gnClass.setAge(new ArrayList<String>());
In all of these cases, assignment to an Integer variable is invalid, hence the compiler error. 在所有这些情况下,分配给Integer变量都是无效的,因此会导致编译器错误。
You only happen to be calling it with an Integer in your example. 在您的示例中,您恰好使用整数来调用它。 The compiler cannot assert that it will always be this way.
编译器不能断言它将一直是这种方式。
It looks as if you should not be using generics at all. 似乎您根本不应该使用泛型。 Just change the signature to
只需将签名更改为
public void setAge(Integer ageParam)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.