I have a double[][] array, and I want to get one row into a float[] array. Casting didn't worked at first, so I looked for something different.
I found here in stackoverflow an elegant solution to convert Object[] to String[], which also would work if I were converting Object[] to float[].
So: is there any elegant way of converting double[] to float[], or a double[] to Object[] so I can use the code at the other post?
I'll provide an example code of what I'm doing, even I think it's not neccesary:
double[][] datos = serie.toArray();
double[][] testArray = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}};
double[] doubleArray = Arrays.copyOf(testArray[1], testArray[1].length);
// This would be great but doesn't exist:
//float[] floatArray = Arrays.copyOf(doubleArray, doubleArray.length, float[].class);
You have to specify the size if you are going to define array float in this way: float array[4]; You can define the array without the size.
An array is a sequence of values; the values in the array are called elements. You can make an array of int s, double s, or any other type, but all the values in an array must have the same type.
getFloat() is an inbuilt method of Array class in Java and is used to return the element present at the given index from the specified Array as Float. Parameters: This method accepts two mandatory parameters: array: The object array whose index is to be returned.
Now my answer was: yes, since you can declare an array of objects and store integers and floats in it.
No, casting the array won't work. You need to explicitly convert each item:
float[] floatArray = new float[doubleArray.length];
for (int i = 0 ; i < doubleArray.length; i++)
{
floatArray[i] = (float) doubleArray[i];
}
With Kotlin you can try something like this:
val doubleArray = arrayOf(2.0, 3.0, 5.0)
val floatArray = doubleArray.map { it.toFloat() }.toFloatArray()
or
val floatArray = arrayOf(2.0, 3.0, 5.0).map { it.toFloat() }.toFloatArray()
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