Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #309 Clone a 2D array

Create the new 2-dimensional array y containing a copy of the elements of the 2-dimensional array x.

x and y must not share memory. Subsequent modifications of y must not affect x.

import static java.lang.System.arraycopy;
import static java.lang.reflect.Array.newInstance;
Class<?> c = x.getClass(),
         a = c.getComponentType(),
         b = a.getComponentType();
int i, m = x.length, n;
T y[][] = (T[][]) newInstance(a, m), Y[], t[];
for (i = 0; i < m; ++i) {
    n = (t = x[i]).length;
    Y = (T[]) newInstance(b, n);
    arraycopy(t, 0, Y, 0, n);
    y[i] = Y;
}
import static java.lang.System.arraycopy;
int i, m = x.length, n,
    y[][] = new int[m][], Y[], t[];
for (i = 0; i < m; ++i) {
    n = (t = x[i]).length;
    Y = new int[n];
    arraycopy(t, 0, Y, 0, n);
    y[i] = Y;
}
import static java.util.Arrays.copyOf;
int i, m = x.length, n,
    y[][] = new int[m][], t[];
for (i = 0; i < m; ++i) {
    n = (t = x[i]).length;
    y[i] = copyOf(t, n);
}
integer, allocatable, dimension(:,:) :: y

y = x

An allocatable array takes the bounds of thr right hand side upon assignment.

New implementation...
< >
programming-idioms.org