Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2004

Tip: Looking for answers? Try searching our database.

copying a class

Thread view: 
Allan Bruce - 09 Mar 2004 15:02 GMT
Is there an easy way to completely copy a class?  say I have;

FOO A;
FOO B;

and I do:

A = new FOO();
// do some changin of member vars

now I want to get a copy of A into B, and be able to modify A but without
changing B.  It seems that using

1) B = A means B and A point to the same object

2) B = A.clone() means that A and B are different objects but their member
vars (e.g. arrays etc.) still point to the same so that if I modify
A.array[0] then B.array[0] is also modified.

I could over-ride clone() and copy over each variable manually but I thought
there may be an easier way?

If not, then are there easy ways to copy Hashtables and arrays?

Thanks
Allan
Eric Sosman - 09 Mar 2004 15:31 GMT
> Is there an easy way to completely copy a class?  say I have;
>
[quoted text clipped - 19 lines]
>
> If not, then are there easy ways to copy Hashtables and arrays?

   clone() is the usual way to copy an object, and the reason
you need to override it is that different classes will need to
have different ideas about what a "copy" is.  You've already
noticed this in point 2 above: a "shallow copy" is one perfectly
reasonable kind of a copy operation, but others can be usefully
defined.  You define the kind of copy you want by implementing
an appropriate clone().

   If you want to copy a HashTable, your first task is to decide
what you mean by a "copy."  One possibility is that you want a
new HashTable with the same content as the old; that's a "shallow
copy."  Another possibility is that you want a new HashTable
containing copies of all the content of the old; that's a "deep
copy."  But even within "deep copy" there are further flavors,
because you need to decide what kind of copy to apply to the
contained objects: are they in turn to be copied shallowly or
deeply?  If one of the contained objects is a String, say, do
you really need a brand-new String containing the same characters,
or will a reference to the original (immutable) String suffice?
What if one of the contained objects is a singleton; are you
really going to (try to) make a second copy of it?

   IMHO, the need to make copies is usually -- not always, but
usually -- a sign that the design could be improved.  Speaking
very loosely, the amount of information in your universe does
not increase when you make photocopies.  If the goal of your
application is (in some vague sense) to develop information,
the act of copying does not in and of itself do so.

Signature

Eric.Sosman@sun.com

Allan Bruce - 09 Mar 2004 17:46 GMT
> > Is there an easy way to completely copy a class?  say I have;
> >
[quoted text clipped - 48 lines]
> application is (in some vague sense) to develop information,
> the act of copying does not in and of itself do so.

Thanks this helps a lot.  One little thing.  How do I make sure I have a
deep copy of an int and String?  Does this work?

String a = "Hello World\n";
String b;
int    c = 100;
int    d;

b = a; // does this copy the string?
d = c; // i assume this is a copy rather than d being a reference to c

Thanks
Allan
Eric Sosman - 09 Mar 2004 19:03 GMT
> Thanks this helps a lot.  One little thing.  How do I make sure I have a
> deep copy of an int and String?  Does this work?
[quoted text clipped - 5 lines]
>
> b = a; // does this copy the string?

   No.  `a' and `b' are references, and both now refer
to the same String object.

> d = c; // i assume this is a copy rather than d being a reference to c

   Yes.  `c' and `d' are primitives, not references, so
each occurrence has its own unique identity.  There is no
underlying Object for an `int' (some purists think there
ought to be, that Java should have been defined differently,
but that's the way things are).

   I find it helpful to think of "reference" as a primitive
type, along with char and boolean and the rest.  In this
world view, `a' is not a String at all; it's a String
*reference* whose value may, from time to time, be changed
so it refers to various different String objects.  Saying
"`a' is a String" is a convenient shorthand, nothing more.
In the True Understanding `a' is a variable that can store
a primitive of the "reference to String" type, and the
String objects themselves are nameless.

   Bad analogy: The reference is your street adress, and
the Object is your house.  You can publish your address in
any number of directories and other places without building
a new house every time you do so.  You can burn one of those
listings without burning down your house.  The reference and
the thing referred to are different entities.

Signature

Eric.Sosman@sun.com

Allan Bruce - 09 Mar 2004 19:41 GMT
> > Thanks this helps a lot.  One little thing.  How do I make sure I have a
> > deep copy of an int and String?  Does this work?
[quoted text clipped - 8 lines]
>     No.  `a' and `b' are references, and both now refer
> to the same String object.

so to make a copy, I need to do this:

b = new String(a);

Is that correct?
Thanks
Allan
Eric Sosman - 09 Mar 2004 20:13 GMT
> > > Thanks this helps a lot.  One little thing.  How do I make sure I have a
> > > deep copy of an int and String?  Does this work?
[quoted text clipped - 14 lines]
>
> Is that correct?

   Yes.  But to return to the question in my first response,
why do you want to make this second and redundant copy of
"Hello World\n"?  The world will not feel twice as welcomed
because you've said the same thing twice ...

Signature

Eric.Sosman@sun.com

Allan Bruce - 09 Mar 2004 20:50 GMT
> > > > Thanks this helps a lot.  One little thing.  How do I make sure I have a
> > > > deep copy of an int and String?  Does this work?
[quoted text clipped - 19 lines]
> "Hello World\n"?  The world will not feel twice as welcomed
> because you've said the same thing twice ...

I do have my reasons.  I`m developing a qualitative reasoning inference
engine and I require to generate a copy of all the variables into a state.
Perhaps I dont need the variable names to be a copy, but everything else
does need to be a deep copy.
Thanks for your help
Allan
S Manohar - 11 Mar 2004 01:13 GMT
> I do have my reasons.  I`m developing a qualitative reasoning inference
> engine and I require to generate a copy of all the variables into a state.
> Perhaps I dont need the variable names to be a copy, but everything else
> does need to be a deep copy.
> Thanks for your help
> Allan

Aha! I had to solve a very similar problem last month. I implemented
Serialisable on my data classes, and simply persisted the object using
Serialisation:

ByteArrayOutputStream baos = new ByteArrayOutputStream()
ObjectOutputStream oos =
 new ObjectOutputStream(       // write whole objects (recursively)
  new ZipOutputStream(         // and compress them (I needed to)
    baos                       // into a byte array
  )
 );
oos.writeObject(myData);                   // process the object
byte[] persistedData = baos.toByteArray(); // and recover the data

This seems to robustly handle deep copies of all data types
automatically. Should you, for some reason, need a shallower copy (I
suppose you should not, if your data classes are properly
encapsulated), then use 'transient' on members that are not to be
persisted, and provide a void readObject(ObjectInputStream) method to
restore the value.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.