Rom*_*dgz 7 java arrays floating-point double
我有一个double [] []数组,我希望将一行放入float []数组中.铸造最初没有起作用,所以我寻找不同的东西.
我在stackoverflow中找到了一个优雅的解决方案,将Object []转换为String [],如果我将Object []转换为float [],它也可以工作.
所以:有没有优雅的方法将double []转换为float [],或者将double []转换为Object [],以便我可以在其他帖子中使用代码?
我将提供一个我正在做的示例代码,即使我认为它不是必要的:
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);
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 24
不,投射阵列将无法正常工作.您需要显式转换每个项目:
float[] floatArray = new float[doubleArray.length];
for (int i = 0 ; i < doubleArray.length; i++)
{
floatArray[i] = (float) doubleArray[i];
}
Run Code Online (Sandbox Code Playgroud)
这是一个可以放在库中并反复使用的函数:
float[] toFloatArray(double[] arr) {
if (arr == null) return null;
int n = arr.length;
float[] ret = new float[n];
for (int i = 0; i < n; i++) {
ret[i] = (float)arr[i];
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)