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);
}
}
The issue is indicated in the code.
Why does Java generics not allow type conversion on generic types?
The problem is deeper than this. Even without the line you highlighted, this program is broken:
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
}
}
Java generics only support reference types as type parameters; the generic method foo() could be rewritten as follows:
<T extends Object> void foo(T[] bar) { ... }
And here's your problem: there's no T
that extends Object
such that an int[]
is a T[]
.
Secondarily, the reason the conversion also fails is that we know nothing about T
, so we don't know that there exists a conversion from T
to double
.
This is because you are not specifiying what the generic type T
is. So by default it will think T is an object type, not a number. It's not possible to cast an object to a double, this makes no sense.
If you change to <T extends Number>
this should work just fine. Although, you might need to have an Integer array rather than a int array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With