flyingfromchina
flyingfromchina

Reputation: 9691

What is the best way to combine several arrays into one single array

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

Upvotes: 0

Views: 503

Answers (2)

Kevin Bourrillion
Kevin Bourrillion

Reputation: 40851

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[]...)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500625

  • 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;
}

Upvotes: 5

Related Questions