0

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 ?

4
  • No, you have to loop. If anything, java guarantees the 100 is contiguous but the 10x10 isn't. Java's int[][] is really c's int**, not an int[][]. Commented Mar 26, 2014 at 21:29
  • Have you tried java.lang.System.arraycopy? tutorialspoint.com/java/lang/system_arraycopy.htm Commented Mar 26, 2014 at 21:29
  • For Java 7, instead of System.arraycopy, you can use java.util.Arrays.copyOfRange(...). This doesn't create multi-dimensional arrays, but it can be used within the loop. Commented Mar 26, 2014 at 21:34
  • Can check and see how java.lang.reflect.Array creates Dimensional Arrays. Then somehow index each dimension. Commented Mar 26, 2014 at 22:06

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.