Java泛型:类型不匹配:无法从整数转换为K. [英] Java generics : Type mismatch: cannot convert from Integer to K
问题描述
$ b
类型不匹配:无法从整数转换为K
我的理解是 K
应处理任何延伸 Number $ c $的值c>。
public< K extends Number> K getValue(){
Integer a = new Integer(1);
return a; //类型不匹配:无法从整数转换为K
}
< (注意:这只是一个测试代码,可以提供我的问题,而不会给出我实际场景的不相关细节。)
K
是一个延伸 Number
的类型,但它是未知因为 Integer
只是一个特定的子类 code> Number
,所以它不能匹配任何潜在的目标类型。 假设你想明确地强制转换它使用
public< K extends Number> K getValue(){
Integer a = new Integer(1);
return(K)a;
}
然后,如果您打电话给期望 Number
除 Integer
以外,您将得到 ClassCastException
,这正是编译器想要的避免:
Double d = getValue(); < - throws ClassCastException
解决方法是使用 Number
public Number getValue(){
return new Integer (1);
}
Following code is throwing compile time exception
Type mismatch: cannot convert from Integer to K
What I understand is K
should handle any value that extends Number
.
public <K extends Number> K getValue(){
Integer a = new Integer(1);
return a;//Type mismatch: cannot convert from Integer to K
}
(Note: This is just a test code to put my question without giving irrelevant details of my actual scenario.)
The problem here is the fact that K
is a type that extends Number
but it is an unknown sub class of Number
that is why the compiler raises this error because Integer
is only one specific sub class of Number
so it cannot match with any potential target types.
Let's say that you want to cast it explicitly to make it compile with
public <K extends Number> K getValue(){
Integer a = new Integer(1);
return (K) a;
}
Then if you call it expecting any sub class of Number
except Integer
you will get a ClassCastException
, that is exactly what the compiler wants to avoid:
Double d = getValue(); <-- throws ClassCastException
As workaround you could define your method using Number
as returned type as next:
public Number getValue() {
return new Integer(1);
}
这篇关于Java泛型:类型不匹配:无法从整数转换为K.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!