gpt4 book ai didi

java - 将一维数组复制到二维数组

转载 作者:行者123 更新时间:2023-12-02 06:00:59 25 4
gpt4 key购买 nike

使用 C/C++ 可以执行以下操作:

int arr[100];
int ar[10][10];
memcpy(ar, arr, sizeof(int)*100);

因为C/C++标准保证数组是连续的,所以上面将一维数组复制到二维数组。

这在 Java 中可能吗?

最佳答案

这在 Java 中是不可能的,因为 Java 中的多维数组实际上是数组的数组。这些元素不存储在连续的内存块中。您需要逐行复制元素。

例如,以下是几种可能的技术之一:

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

来自Java Language Specification, §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.

  • 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.

  • 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).

  • 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.

关于java - 将一维数组复制到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22673406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com