Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top