Re: [問題] 關於.clone的問題?

看板java作者 (-858993460)時間12年前 (2012/05/03 18:19), 編輯推噓1(103)
留言4則, 3人參與, 最新討論串2/2 (看更多)
陣列的 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

05/03 18:27, , 1F
所以說n維陣列就要在第n-1維的地方做clone(),這樣嗎?
05/03 18:27, 1F

05/03 18:29, , 2F
疑,好像還要看是基本型態的陣列還是物件陣列...
05/03 18:29, 2F

05/03 18:48, , 3F
或者可以直接deep clone
05/03 18:48, 3F

05/04 00:21, , 4F
好有深度XD...我在想一下 謝謝
05/04 00:21, 4F
文章代碼(AID): #1FebkipC (java)
文章代碼(AID): #1FebkipC (java)