[英]Copy 1D array to 2D array
Using C/C++ it is possible to do the following: 使用C / C ++可以执行以下操作:
int arr[100];
int ar[10][10];
memcpy(ar, arr, sizeof(int)*100);
Because the C/C++ standard guarantees that arrays are contiguous, the above will copy 1D array to 2D array. 因为C / C ++标准保证数组是连续的,所以上面会将1D数组复制到2D数组。
Is this possible in Java ? 这在Java中可行吗?
This is not possible in Java because a multidimensional array in Java is actually an array of arrays. 这在Java中是不可能的,因为Java中的多维数组实际上是一个数组数组。 The elements are not stored in a contiguous block of memory. 元素不存储在连续的内存块中。 You will need to copy the elements row by row. 您需要逐行复制元素。
For example, here's one of several possible techniques: 例如,以下是几种可能的技术之一:
int arr[100] = . . .;
int ar[10][10] = new int[10][10];
int offset = 0;
for (int[] row : ar) {
System.arraycopy(arr, offset, row, 0, row.length);
offset += row.length;
}
From the Java Language Specification, §15.10.1 , here are the steps that happen when evaluating the array creation expression new int[10][10]
(note in particular the last point): 从Java语言规范,§15.10.1 ,这里是评估数组创建表达式new int[10][10]
时发生的步骤(特别注意最后一点):
First, the dimension expressions are evaluated, left-to-right. 首先,从左到右评估维度表达式。 If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated. 如果任何表达式评估突然完成,则不评估其右侧的表达式。
Next, the values of the dimension expressions are checked. 接下来,检查维度表达式的值。 If the value of any DimExpr expression is less than zero, then a NegativeArraySizeException is thrown. 如果任何DimExpr表达式的值小于零,则抛出NegativeArraySizeException。
Next, space is allocated for the new array. 接下来,为新阵列分配空间。 If there is insufficient space to allocate the array, evaluation of the array creation expression completes abruptly by throwing an OutOfMemoryError. 如果没有足够的空间来分配数组,则通过抛出OutOfMemoryError突然完成对数组创建表达式的求值。
Then, if a single DimExpr appears, a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5). 然后,如果出现单个DimExpr,则创建具有指定长度的一维数组,并将数组的每个组件初始化为其默认值(第4.12.5节)。
Otherwise, if n DimExpr expressions appear, then array creation effectively executes a set of nested loops of depth n-1 to create the implied arrays of arrays. 否则,如果出现n个DimExpr表达式,则数组创建有效地执行一组深度为n-1的嵌套循环,以创建隐含的数组数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.