Re: [問題] 關於.clone的問題?
陣列的 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
05/03 18:27, 1F
→
05/03 18:29, , 2F
05/03 18:29, 2F
→
05/03 18:48, , 3F
05/03 18:48, 3F
→
05/04 00:21, , 4F
05/04 00:21, 4F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):