The most intelligent Java IDE
The moose likes Performance and the fly likes Best way to get copy of an object? The Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Performance
Reply Bookmark "Best way to get copy of an object?" Watch "Best way to get copy of an object?" New topic
Author

Best way to get copy of an object?

ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3792
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 ]
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 10634
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

Java Resources at www.wbrogden.com
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3792



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.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 10634
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
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3792
Thanks a lot William.
It was really nice explanation.
 
jQuery in Action, 2nd edition
 
subject: Best way to get copy of an object?