How can I deep copy an irregularly shaped 2D array in Java?
Ie.
int[][] nums = {{5},
{9,4},
{1,7,8},
Here's one that specializes to deeply cloning int[][]
. It also allows any of the int[]
to be null
.
import java.util.*;
public class ArrayDeepCopy {
static int[][] clone(int[][] arr) {
final int L = arr.length;
int[][] clone = new int[L][];
for (int i = 0; i < clone.length; i++) {
clone[i] = (arr[i] == null) ? null : arr[i].clone();
}
return clone;
}
public static void main(String[] args) {
int[][] a = {
{ 1, },
{ 2, 3, },
null,
};
int[][] b = a.clone();
System.out.println(a[0] == b[0]); // "true", meaning shallow as expected!
b = clone(a); // this is deep clone!
System.out.println(Arrays.deepEquals(a, b)); // "true"
System.out.println(a[0] == b[0]); // "false", no longer shallow!
}
}