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

2019-08-03 18:29发布

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 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.

2条回答
淡お忘
2楼-- · 2019-08-03 19:09

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
查看更多
狗以群分
3楼-- · 2019-08-03 19:12

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

查看更多
登录 后发表回答