Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best way to get copy of an object?

 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot William.
It was really nice explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic