List值的TreeMap构造函数

时间:2013-04-17 15:22:39

标签: java list constructor treemap

我有Class1私有属性TreeMap<Long, List<Class2>> tree;和其他人,我想写一个构造函数Class1(Class1 copyOfClass1)。我应该明确地创建List的{​​{1}}值(例如,在循环中),还是使用TreeMap那样做?

1 个答案:

答案 0 :(得分:1)

如果您使用this.tree=new TreeMap(copyOfClass1.tree),它将等同于

this.tree=new TreeMap();
this.tree.putAll(copyOfClass1.tree)

但是,它不会复制存储在地图中的列表。键将指向相同的列表。

如果你不想要这种行为,我会建议迭代这些条目并制作一份清单。

    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()));
    }
相关问题