简体   繁体   中英

Copy 1D array to 2D array

Using C/C++ it is possible to do the following:

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.

Is this possible in Java ?

This is not possible in Java because a multidimensional array in Java is actually an array of arrays. 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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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