Question

If I have a function that takes a double as an argument, I can easily put in a float.

However when I have a funcion that takes a double[] then I cannot pass a float[].

public static void doSomethingWithMyDoubles(double[] doubles) {
    //....
}

public static void doSomethingWithMyDouble(double doubles) {
    //....
}

public static void main() {
    float floater = 10f;
    double doubler = 10d;

    doSomethingWithMyDouble(doubler) // OK
    doSomethingWithMyDouble(floater) // OK

    float[] floates = new float[10];
    double[] doubles = new double[10];

    doSomethingWithMyDoubles(doubles) // OK
    doSomethingWithMyDoubles(floates) // NOK
}
Was it helpful?

Solution

In Java, arrays are not a primitive data type; instead they are of type Object. As a consequence, you cannot convert an array of one primitive type to an array of another primitive type directly (even though you might cast the individual elements in the array to the other type).

OTHER TIPS

It is because implicite type conversion takes place when you pass float value into the method whitch requires double one. But there is no type conversion between float[] and double[] arrays.

A float is a 4-byte type, and a double is an 8-byte type. Widening a single float to a double is a constant-time operation. However, widening a float[] to a double[] has to do a full copy, and needs to take linear time to widen the entire array. So Java won't do it implicitly -- it won't pretend that the operation is as cheap as an O(1) operation.

That is because float and doubles are primitives. Floats can be automatically casted into doubles. However, double[] and float[] are objects. Try explicitly casting. You may need to iterate and cast each element and insert into your new array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top