I have a Class1
with private attribute TreeMap<Long, List<Class2>> tree;
and others, I want to write a constructor Class1(Class1 copyOfClass1)
. Should I create the List
values of the TreeMap
explicitly (e.g., in a loop), or using this.tree=new TreeMap(copyOfClass1.tree)
does that?
Asked
Active
Viewed 383 times
0

aLogic
- 125
- 1
- 8
-
Do you want a deep copy or shallow copy? – Sotirios Delimanolis Apr 17 '13 at 15:26
1 Answers
1
If you use this.tree=new TreeMap(copyOfClass1.tree)
it will be equivalent as
this.tree=new TreeMap();
this.tree.putAll(copyOfClass1.tree)
However, it will not make a copy of the list that are stored in the map. The keys will be pointing to the same lists.
If you dont want this behavior I would suggest to iterate over the entries and to make a copy of the lists.
this.tree = new TreeMap<Long, List<Class2>>();
for (Entry<Long, List<Class2>> entry : copyOfClass1.tree.entrySet()) {
this.tree.put(entry.getKey(), new ArrayList<Class2>(entry.getValue()));
}

Xavier Delamotte
- 3,519
- 19
- 30
-
And if instead of List I am using another class that I have created, do I need to do the same? I mean, only primitive types are copied by value? – aLogic Apr 17 '13 at 15:45
-
Yes you need to do the same. About the "copy by value": "Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value." http://stackoverflow.com/questions/40480/is-java-pass-by-reference – Xavier Delamotte Apr 17 '13 at 15:55