简体   繁体   English

将多个阵列合并为一个阵列的最佳方法是什么

[英]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? 嗨,我正在尝试将多个double类型的数组合并为一个数组,什么是最好的方法? 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. 重复调用System.arraycopy将一个源数组复制到目标数组中,从而在每次迭代时更新复制它的位置。

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

您可以从Guava库使用此方法,该库是开源的,并且可能在本月晚些时候发布实际的二进制版本: Doubles.concat(double [] ...)

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

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