作者LPH66 (-858993460)
看板java
标题Re: [问题] 关於.clone的问题?
时间Thu May 3 18:19:21 2012
阵列的 clone() 用的是 Object.clone()
而以下是 Object.clone() 的说明:
The method clone for class Object performs a specific cloning operation.
First, if the class of this object does not implement the interface
Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays
are considered to implement the interface Cloneable and that the return type
of the clone method of an array type T[] is T[] where T is any reference or
primitive type. Otherwise, this method creates a new instance of the class of
this object and initializes all its fields with exactly the contents of the
corresponding fields of this object, as if by assignment; the contents of the
fields are not themselves cloned.
Thus, this method performs a "shallow copy"
of this object, not a "deep copy" operation.
太多字不想看的话看标亮黄色的那一句就好:
它做的是 shallow copy 也就是每个成员直接指定过去而已
由於 Java 的多维阵列是阵列的阵列
因此 clone 一个 int[][] 只会开一个新的 int[][] 物件
然後把里面每个 int[] 给指定过去
所以在你的例子里 即使 b = a.clone(); 了
但 b[0] 和 a[0] 却是指到同样的一个一维阵列
这就造成你看到的现象了
--
LPH [acronym]
= Let Program Heal us
-- New Uncyclopedian Dictionary, Minmei Publishing Co.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.28.91
1F:推 risker760915:所以说n维阵列就要在第n-1维的地方做clone(),这样吗? 05/03 18:27
2F:→ risker760915:疑,好像还要看是基本型态的阵列还是物件阵列... 05/03 18:29
3F:→ mars90226:或者可以直接deep clone 05/03 18:48
4F:→ soso0316:好有深度XD...我在想一下 谢谢 05/04 00:21