Shallow vs. deep copy

Question: I have questions about shallow copy and deep copy. Consider the following code:

Vector v = new Vector();
Vector v2 = v;


Is this the only way to make a shallow copy?

Answer: Actually, you have not done a shallow copy at all. Rather, by creating v and v2 , you have created a second reference to the same object. A shallow copy will make a complete copy of the object and any primitive attribute. It will not, however, make copies of any high-level object attributes. Instead, it points those attributes at the reference in the original object.

For a good introduction to how Java treats references, read: "Does Java pass by reference or pass by value? " (JavaWorld, May 26, 2000).

發佈了5 篇原創文章 · 獲贊 4 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章