Search code examples
javacastingwrapper

Can't cast Integer into Double (Wrapper class)


I tried to create a function which return a random int between x and y if x and y are integer but if x or y is a double the function return a double between x and y. But when I try with a integer it throw an Exception:

"class java.lang.Integer cannot be cast to class java.lang.Double (java.lang.Integer and java.lang.Double are in module java.base of loader 'bootstrap')"

how can I fix it?

public class Test {
    public static void main(String[] args) {
        System.out.print(rand(10,12.0));
    }
    public static<t extends Number> double rand(t x,t y) {
        double a = (double) x;
        double b = (double) y;
        b = a < b ?(a + (b - a) * Math.random()):(b + (a - b) * Math.random());
        return (x instanceof Double || y instanceof Double) ? b : (int) b;
    }
}

Solution

  • The problem is that you are working with reference types (wrapper classes) instead of primitive types. A cast from int to double works, but a cast from Integer to Double doesn't. So you will need to find some other way to convert this.

    Since you define t extends Number, you can use any method of Number for x and y.

    So instead of casting to double, use this:

    public static<t extends Number> double rand(t x,t y) {
      double a = x.doubleValue();
      double b = y.doubleValue();