Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java generics not allow type conversion on generic types?

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?

like image 901
xmllmx Avatar asked Mar 25 '16 03:03

xmllmx


2 Answers

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.

like image 74
Brian Goetz Avatar answered Oct 14 '22 09:10

Brian Goetz


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

like image 40
Gaktan Avatar answered Oct 14 '22 09:10

Gaktan