File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Performance and the fly likes Best way to get copy of an object? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
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: 3830
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: 12803
    
    5
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
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830



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: 12803
    
    5
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: 3830
Thanks a lot William.
It was really nice explanation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Best way to get copy of an object?