Forums Register Login

Best way to get copy of an object?

+Pie Number of slices to send: Send
what is the best way to get a copy of an object, in terms of performance, best practices, efficiency and everything...

1] clone() method.
2] create new instance of that object and populate with same value.
3] copying object into stream and then reading from stream.

Please help me out.
If you know any other way also to do this please tell me.
Thanks a lot.
[ May 31, 2005: Message edited by: rathi ji ]
+Pie Number of slices to send: Send
Assuming you want a "deep" copy (all reference variables point to new objects), I would go with 2.
1. clone will only produce a shallow copy
3. serialization requires way too much extra object creation

For 2, why not a constructor that takes an existing object reference as input - naturally this involves more program code but you can control how deep the copy is.
Bill
+Pie Number of slices to send: Send



AddressBook ab1 = new AddressBook();

Shallow Copy:
------------
AddressBook ab2 = ab1.clone();
Does it means that two address book object having single person object.

Deep Copy:
---------
New address book object will have its own person object.

Please correct me if I am wrong.

Thanks a lot.
+Pie Number of slices to send: Send
Yes, "shallow" copy means the reference in the copy points to the same object as the reference in the original. "Deep" copy means the copy has references to completely separate objects.
Whether or not this is important depends on the types of the references - it won't matter for String since String objects are immutable, there is no need to create a new String copy since the character contents can't be changed.
Bill
+Pie Number of slices to send: Send
Thanks a lot William.
It was really nice explanation.
I've got no option but to sell you all for scientific experiments. Or a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 12184 times.
Similar Threads
DefaultMutableTreeNode question...
Welcome Richard
JBoss in Action
Understanding superclass and subclass objects
k&b mock exams
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 03:16:01.