看板 java 關於我們 聯絡資訊
陣列的 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
risker760915:所以說n維陣列就要在第n-1維的地方做clone(),這樣嗎? 05/03 18:27
risker760915:疑,好像還要看是基本型態的陣列還是物件陣列... 05/03 18:29
mars90226:或者可以直接deep clone 05/03 18:48
soso0316:好有深度XD...我在想一下 謝謝 05/04 00:21