• Post Reply Bookmark Topic Watch Topic
  • New Topic

Deep Copy - String and colone() ?  RSS feed

 
Pourang Emami
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How come that in the following code by cloning the vector inside clone(), all Strings elements of that Vector are coloned automatically without explicitly cloning them by navigating through the Vector?

import java.util.Vector;

public class Address implements Cloneable
{

private Vector itsLines = new Vector();

public void setLine(int n, String line)
{
if (n >= itsLines.size())
itsLines.setSize(n+1);
itsLines.setElementAt(line, n);
}//setLine()

public Object clone() throws CloneNotSupportedException
{
Address clone = (Address)super.clone();
clone.itsLines = (Vector)itsLines.clone();
return clone;
}//clone()

}//class
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The contents of the Vector aren't cloned. The array inside the Vector is copied, but not the objects contained by that array. Vector overrides clone() and in that clone() method, the array is copied (or rather, a new array, just the right size to hold the data, is created and the old array's contents are copied.)
 
Pourang Emami
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So do both Vectors (the original and clonned one) contain references to the same String Objects?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found this appendix to Bruce Eckel's Thinking in Java to be helpful in understanding cloning issues...

http://www.faqs.org/docs/think_java/TIJ319.htm
 
Pourang Emami
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!