开发者

In Java, I want to convert a short[] to a double[]

开发者 https://www.devze.com 2023-01-30 00:30 出处:网络
I am using a short[] array: short[] buffer = new short[bufferSize]; I have a method that takes as a parameter type double[], so I cannot pass it as-is.I need to make it into a开发者_如何学Go double

I am using a short[] array:

short[] buffer = new short[bufferSize];

I have a method that takes as a parameter type double[], so I cannot pass it as-is. I need to make it into a开发者_如何学Go double[]. The best thing that I've done is to make a new object and loop through and convert, like this:

double[] transformed = new double[bufferSize];

for (int j=0;j<bufferSize;j++) {
    transformed[j] = (double)buffer[j];
}

I have not yet even tested the above approach, but I am wondering if there is a better way to do this?

Thanks.


That's as good as it gets, though you can just use buffer.length instead of buffersize.


The answer provided by Laurence is correct and should be accepted, but it's worth noting that there is more than one way to copy an array in Java. See this article for an explanation of each method.

  • use the various copyOf and copyOfRange methods of the Arrays class
  • use System.arraycopy - useful when copying parts of an array
  • call its clone method, and do a cast - the simplest style, but only a shallow clone is performed
  • use a for loop - more than one line, and needs a loop index
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号