简体   繁体   English

创建一个新的2D数组= 2D数组1的大小+ 2d数组2的大小(行和列)

[英]Creating a new 2D array that = size of 2D array 1 + size of 2d array 2 (rows and columns)

public static int[][] add2DArrays(int[][]A, int[][]B) {
        return int[][] C;
}

I understand how to populate this new array by adding the sums of the two arrays A & B, the road block I am facing is creating this initial array C. We cannot assume the size of the arrays given as parameters, so that is the part I am having a problem with. 我了解如何通过将两个数组A和B的和相加来填充此新数组,我面临的障碍是创建此初始数组C。我们无法假定作为参数给出的数组的大小,因此这是一部分我有问题。

I know by doing: 我知道这样做:

 int[][] C = new int[A.length+B.length][]; //this will only give me the # of rows;

I am stuck on how to get the proper length of columns for the rows in the new array. 我被困在如何为新数组中的行获取适当的列长。 I am thinking it may be possible to some how record the length of the longest row in A, and then record the longest row in B, and choose the bigger of the two, but that seems messy and inefficient. 我认为可能有可能如何记录A中最长的行的长度,然后记录B中最长的行,然后选择两者中的较大者,但这似乎很麻烦且效率低下。 Thank you all for your support. 谢谢大家的支持。

If both are really 2D arrays -- that is, the length of all the rows is the same -- and row 0 was actually allocated, you can get the summed length of a row from A[0].length+B[0].length 如果两个都是真正的2D数组-也就是说,所有行的长度都相同-并且实际上已分配了行0,则可以从A[0].length+B[0].length获取行的总长度。 A[0].length+B[0].length

If the length of the rows might vary -- which is perfectly legal in Java -- then you might need to iterate through A and B to find the longest row and use that length. 如果行的长度可能有所不同-这在Java中是完全合法的-那么您可能需要遍历A和B以找到最长的行并使用该长度。

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

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