JobNick
JobNick

Reputation: 503

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 ?

Upvotes: 0

Views: 2456

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

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.

Upvotes: 2

Related Questions