简体   繁体   中英

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?

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

The Java compiler erases all type parameters in generic code. A direct consequence of this is that you cannot verify which parameterized type for a generic is currently is use. If you test, instanceof will not work either. Since, runtime does not keep track of a type parameters in java, there is no difference between HashSet<Integer> and HashSet<Double> . You can do a ..instanceof HashSet<?> at the most to check if it is an instance of a HashSet.

If something is not clear in what I have written, please refer to the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM