简体   繁体   English

在Java中,我想将short []转换为double []

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

I am using a short[] array: 我正在使用short[]数组:

short[] buffer = new short[bufferSize];

I have a method that takes as a parameter type double[] , so I cannot pass it as-is. 我有一个将double[]作为参数类型的方法,所以我不能按原样传递它。 I need to make it into a double[] . 我需要使其成为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. 谢谢。

尽管您可以只使用buffer.length而不是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. Laurence提供的答案是正确的,应该接受,但是值得注意的是,在Java中复制数组的方法不止一种。 See this article for an explanation of each method. 请参见文章对每种方法的说明。

  • use the various copyOf and copyOfRange methods of the Arrays class 使用Arrays类的各种copyOf和copyOfRange方法
  • use System.arraycopy - useful when copying parts of an array 使用System.arraycopy-在复制数组的部分时很有用
  • call its clone method, and do a cast - the simplest style, but only a shallow clone is performed 调用其clone方法,并进行强制转换-最简单的样式,但仅执行浅表克隆
  • use a for loop - more than one line, and needs a loop index 使用for循环-多于一行,并且需要一个循环索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM