I have a treeSet of custom objects. Each custom object is made up of int a, int b, String c and double d. Lets say I have a treeSet object t1 containing 10 such custom objects. I also have another TreeSet object t2 which is empty. what is the best way of copying the objects in treeset t1 into treeset t2... I want new objects in t2 and not just refernces to the ones in t1.one way is to create 10 new objects in t2 and copy the values of all the a's and b's and c's and d's of each of the 10 objects in t1 to those in t2. Any better way?
5 Answers
This technique is known as "deep copying" and there's a good Stack Overflow question on it here.
The current top two answers provide two good perspectives:
- Serialize your objects and then deserialize them (efficient, but not 100% reliable) -- link to answer
- or you'll just have to traverse the whole object and do it manually (as reliable as you can get but not super-simple to do) -- link to answer

- 1
- 1

- 55,313
- 14
- 116
- 115
-
If i do not have any references in the custom objects, just integers and strings and doubles, then do I need to serialize and deserialize? – aps Jun 24 '11 at 17:56
for (Item item : collection) {
newCollection.add(BeanUtils.cloneBean(item));
}
where BeanUtils
is from commons-beanutils

- 55,313
- 14
- 116
- 115

- 588,226
- 146
- 1,060
- 1,140
-
-
1no - nothing else, just the above code. Of course, your class should conform to the javabeans spec - getter and setter for each property. – Bozho Jun 24 '11 at 18:16
-
-
1
Depends on what you mean by better. The best solution is to make the object immutable and just copy the references.
An alternative is to generate or write a copy constructor. The copy constructor can use reflections to copy all the fields.
For the field types you have, you can make the Object Cloneable and use the clone() methods. (Because the fields are primitives or immutable)

- 525,659
- 79
- 751
- 1,130
You already got your answer.
However this process is best to be implemented in the clone() method. So all your object should overwrite this method.
See an example here: http://www.roseindia.net/java/example/java/util/clone-method-example-in-java.shtml

- 8,668
- 13
- 53
- 79