tags:

views:

175

answers:

2

Hey, I was trying to combine several arrays of type double into one single array, what is the best way to do it? Thanks!

+4  A: 
  • Create an array of the right size (by going through and summing the lengths of all the source arrays)
  • Repeatedly call System.arraycopy to copy one source array at a time into the target array, updating the place where you copy it to on each iteration.

So something like:

public static double[] Combine(double[][] arrays)
{
    int totalLength = 0;
    for (double[] source : arrays)
    {
        totalLength += source.length;
    }
    double[] ret = new double[totalLength];
    int index = 0;
    for (double[] source : arrays)
    {
        System.arraycopy(source, 0, ret, index, source.length);
        index += source.length;
    }
    return ret;
}
Jon Skeet
I smell integer overflow!
erickson
Wouldn't an overflow only occur if there's about 16 GB of data?
JRL
Never underestimate the constraints on your inputs: http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
Andrzej Doyle
Do you mean overflow of the totalLength?
Thomas Jung
Well, I was just kidding, but yes, you'd need 16 GB of doubles to overflow. However, I'm sure that there are applications that do. I think one of the improvements for JDK 7 is arrays with a `long` length.
erickson
This feature was dropped. Would check it anyway -> http://en.wikipedia.org/wiki/Ariane_5_Flight_501
Thomas Jung
+1  A: 

You can use this method from the Guava library, which is open-source and will have an actual binary release probably later this month: Doubles.concat(double[]...)

Kevin Bourrillion