开发者

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

He开发者_运维百科y, I was trying to combine several arrays of type double into one single array, what is the best way to do it? Thanks!


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜