如何在Java中将浮点数组转换为双精度数组? [英] How to convert array of floats to array of doubles in Java?

查看:124
本文介绍了如何在Java中将浮点数组转换为双精度数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点数组,我想将它转换为Java中的双精度数组。我知道迭代数组并创建一个新数组的明显方法。我希望Java能够顺利地消化一个float [],它希望使用double [] ......但它不能用于此。
这种转换的优雅,有效方法是什么?

解决方案

基本上某事必须进行每个值的转换。两种数组类型之间没有隐式转换,因为在JITting之后用于处理它们的代码会有所不同 - 它们具有不同的元素大小,而float需要转换,而double则不需要。将此与参考类型的数组协方差进行比较,其中在读取数据时不需要转换(例如,对于作为对象引用的字符串引用,位模式相同),并且所有引用类型的元素大小相同。 / p>

简而言之,某些东西必须在循环中执行转换。我不知道有任何内置的方法来做到这一点。我确定它们存在于某个地方的第三方库中,但除非您恰好使用其中一个库,否则我只想编写自己的方法。为方便起见,这是一个示例实现:

  public static double [] convertFloatsToDoubles(float [] input)
{
if(input == null)
{
return null; //或抛出异常 - 你的选择
}
double [] output = new double [input.length];
for(int i = 0; i< input.length; i ++)
{
output [i] = input [i];
}
返回输出;
}


I have an array of floats and I would like to convert it to an array of doubles in Java. I am aware of the obvious way of iterating over the array and creating a new one. I expected Java to digest a float[] smoothly where it wishes to work with double[]... but it can not work with this. What is the elegant, effective way of doing this conversion?

解决方案

Basically something has to do the conversion of each value. There isn't an implicit conversion between the two array types because the code used to handle them after JITting would be different - they have a different element size, and the float would need a conversion whereas the double wouldn't. Compare this to array covariance for reference types, where no conversions are required when reading the data (the bit pattern is the same for a String reference as an Object reference, for example) and the element size is the same for all reference types.

In short, something will have to perform conversions in a loop. I don't know of any built-in methods to do this. I'm sure they exist in third party libraries somewhere, but unless you happen to be using one of those libraries already, I'd just write your own method. For the sake of convenience, here's a sample implementation:

public static double[] convertFloatsToDoubles(float[] input)
{
    if (input == null)
    {
        return null; // Or throw an exception - your choice
    }
    double[] output = new double[input.length];
    for (int i = 0; i < input.length; i++)
    {
        output[i] = input[i];
    }
    return output;
}

这篇关于如何在Java中将浮点数组转换为双精度数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆