xml*_*lmx 10 java generics type-conversion
public class Main {
public static <T> void foo(T[] bar) {
double d = (double) bar[0]; // Error : incompatible types
}
public static void main(String[] args) {
int[] int_buf = new int[8];
foo(int_buf);
}
}
Run Code Online (Sandbox Code Playgroud)
问题在代码中指出.
为什么Java泛型不允许对泛型类型进行类型转换?
Bri*_*etz 15
问题比这更深刻.即使没有突出显示的行,此程序也会被破坏:
public class Main {
public static <T> void foo(T[] bar) {
// do nothing
}
public static void main(String[] args) {
int[] int_buf = new int[8];
foo(int_buf); <-- problem is here
}
}
Run Code Online (Sandbox Code Playgroud)
Java泛型仅支持引用类型作为类型参数; 泛型方法foo()可以重写如下:
<T extends Object> void foo(T[] bar) { ... }
Run Code Online (Sandbox Code Playgroud)
这就是你的问题:没有任何T扩展Object,以至于a int[]是a T[].
其次,转换也将失败的原因是,我们并不知道T,所以我们不知道存在从转换T到double.
Gak*_*tan 13
这是因为您没有指定泛型类型T.因此,默认情况下,它会认为T是对象类型,而不是数字.将对象强制转换为double是不可能的,这没有任何意义.
如果你改为<T extends Number>这应该工作得很好.虽然,您可能需要一个Integer数组而不是一个int数组
| 归档时间: |
|
| 查看次数: |
626 次 |
| 最近记录: |