Reputation: 125
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?
Upvotes: 0
Views: 396
Reputation: 3599
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()));
}
Upvotes: 1