猿问

Java泛型数组深拷贝和克隆泛型对象

我想做一个 n 维原始数组的深层副本。


public static double[] deepCopy(double[] arr) {

    return arr.clone();

}


public static double[][] deepCopy(double[][] arr) {

    arr = arr.clone();

    for (int i = 0; i < arr.length; i++) {

        arr[i] = deepCopy(arr[i]);

    }

    return arr;

}


public static double[][][] deepCopy(double[][][] arr) {

    arr = arr.clone();

    for (int i = 0; i < arr.length; i++) {

        arr[i] = deepCopy(arr[i]);

    }

    return arr;

}

以上是深度复制1、2、3维双数组的代码。我想概括任何原始类型和/或概括数组的维度。我想要两者,但我知道 Java 中有很多东西是不可能的,所以如果你只能得到一个也没关系,或者告诉我为什么它不起作用。


海绵宝宝撒
浏览 374回答 1
1回答

梦里花落0921

要深度复制多维数组,请使用以下代码。请注意,这只是数组值的深度副本,而不是数组中任何非数组值的副本,因此副本仅对于多维原始数组才是真正的深度副本。对于多维对象数组,它是深浅的。数组的声明类型无关紧要。例如, anObject[][]可以包含数组对象,使其(部分)成为 3D 数组。那些第三维数组也被复制。该方法将复制一维对象数组,但不会复制一维原始数组。要复制一维原始数组,请使用clone().@SuppressWarnings("unchecked")public static <T> T[] deepCopyArray(T[] array) {&nbsp; &nbsp; return (T[]) deepCopyArrayInternal(array);}private static Object deepCopyArrayInternal(Object array) {&nbsp; &nbsp; int length = Array.getLength(array);&nbsp; &nbsp; Object copy = Array.newInstance(array.getClass().getComponentType(), length);&nbsp; &nbsp; for (int i = 0; i < length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; Object value = Array.get(array, i);&nbsp; &nbsp; &nbsp; &nbsp; if (value != null && value.getClass().isArray())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value = deepCopyArrayInternal(value);&nbsp; &nbsp; &nbsp; &nbsp; Array.set(copy, i, value);&nbsp; &nbsp; }&nbsp; &nbsp; return copy;}
随时随地看视频慕课网APP

相关分类

Java
我要回答