在 Java 中深度克隆多维数组...?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/200387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deep cloning multidimensional arrays in Java...?
提问by
I have two multidimensional arrays (well actually they're only 2D) which have inferred size. How do I deep clone them? Here's what I have gotten so far:
我有两个推断大小的多维数组(实际上它们只是二维数组)。我如何深度克隆它们?这是我到目前为止所得到的:
public foo(Character[][] original){
clone = new Character[original.length][];
for(int i = 0; i < original.length; i++)
clone[i] = (Character[]) original[i].clone();
}
A test for equality original.equals(clone);spits out a false. Why? :|
平等的测试original.equals(clone);吐出一个错误。为什么?:|
回答by
/**Creates an independent copy(clone) of the boolean array.
* @param array The array to be cloned.
* @return An independent 'deep' structure clone of the array.
*/
public static boolean[][] clone2DArray(boolean[][] array) {
int rows=array.length ;
//int rowIs=array[0].length ;
//clone the 'shallow' structure of array
boolean[][] newArray =(boolean[][]) array.clone();
//clone the 'deep' structure of array
for(int row=0;row<rows;row++){
newArray[row]=(boolean[]) array[row].clone();
}
return newArray;
}
回答by abahgat
You might want to check out the java.util.Arrays.deepEqualsand java.util.Arrays.equalsmethods.
您可能想查看java.util.Arrays.deepEquals和java.util.Arrays.equals方法。
I'm afraid the equalsmethod for array objects performs a shallow comparison, and does not properly (at least for this case) compare the inner Characterarrays.
恐怕equals数组对象的方法执行浅比较,并且没有正确(至少在这种情况下)比较内部Character数组。
回答by gizmo
equals() method on arrays is the one declared in Object class. This means that it will only returns true if the object are the same. By the same it means not the same in CONTENT, but the same in MEMORY. Thus equals() on your arrays will never return true as you're duplicating the structure in memory.
数组上的 equals() 方法是在 Object 类中声明的方法。这意味着它只会在对象相同时返回 true。同样的意思是在内容上不一样,但在记忆中是一样的。因此,当您在内存中复制结构时,数组上的 equals() 永远不会返回 true。
回答by Andreas Petersson
A test for equality original.equals(clone); spits out a false. Why? :|
相等的测试 original.equals(clone); 吐出一个假的。为什么?:|
thats because you are creating a new array with new Character[original.length][];.
那是因为您正在使用new Character[original.length][];.
Arrays.deepEquals(original,clone)should return true.
Arrays.deepEquals(original,clone)应该返回true。
回答by Venkata Raju
Same as @Barak solution (Serialize and Deserialize) with examples (as some people could not understand and down voted that)
与带有示例的@Barak 解决方案(序列化和反序列化)相同(因为有些人无法理解并否决了这一点)
public static <T extends Serializable> T deepCopy(T obj)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
ObjectOutputStream oos = new ObjectOutputStream(baos);
// Beware, this can throw java.io.NotSerializableException
// if any object inside obj is not Serializable
oos.writeObject(obj);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(baos.toByteArray()));
return (T) ois.readObject();
}
catch ( ClassNotFoundException /* Not sure */
| IOException /* Never happens as we are not writing to disc */ e)
{
throw new RuntimeException(e); // Your own custom exception
}
}
Usage:
用法:
int[][] intArr = { { 1 } };
System.out.println(Arrays.deepToString(intArr)); // prints: [[1]]
int[][] intDc = deepCopy(intArr);
intDc[0][0] = 2;
System.out.println(Arrays.deepToString(intArr)); // prints: [[1]]
System.out.println(Arrays.deepToString(intDc)); // prints: [[2]]
int[][] intClone = intArr.clone();
intClone[0][0] = 4;
// original array modified because builtin cloning is shallow
System.out.println(Arrays.deepToString(intArr)); // prints: [[4]]
System.out.println(Arrays.deepToString(intClone)); // prints: [[4]]
short[][][] shortArr = { { { 2 } } };
System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]]
// deepCopy() works for any type of array of any dimension
short[][][] shortDc = deepCopy(shortArr);
shortDc[0][0][0] = 4;
System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]]
System.out.println(Arrays.deepToString(shortDc)); // prints: [[[4]]]
回答by Barak Schiller
I found this answer for cloning multidimensional arrays on jGuru:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object deepCopy = ois.readObject();

