Java List.set替换树映射中的所有索引

Java List.set替换树映射中的所有索引,java,dictionary,treemap,Java,Dictionary,Treemap,我有一个TreeMap你做的一切都对。此外,您还可以删除myMap.put(specificKey,doubleList),因为列表已经存在 在您的场景中发生这种情况的原因是,所有三个键都引用了您在填充树映射时创建的列表的同一个实例。更改代码以为每个密钥插入新列表以解决此问题: myMap.put(specificKey1, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0)))); myMap.put(spe

我有一个
TreeMap你做的一切都对。此外,您还可以删除myMap.put(specificKey,doubleList)
,因为列表已经存在

在您的场景中发生这种情况的原因是,所有三个键都引用了您在填充
树映射时创建的
列表的同一个实例。更改代码以为每个密钥插入新列表以解决此问题:

myMap.put(specificKey1, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0))));
myMap.put(specificKey2, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0))));
myMap.put(specificKey3, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0))));
...
if (myMap.containsKey(specificKey1){
    myMap.get(specificKey1).set(0, someValue);
}
myMap.put(specificKey1,新的ArrayList(Collections.nCopies(3,Double.valueOf(0)));
put(specificKey2,新的ArrayList(Collections.nCopies(3,Double.valueOf(0));
put(specificKey3,新的ArrayList(Collections.nCopies(3,Double.valueOf(0));
...
if(myMap.containsKey(specificKey1){
获取(specificKey1).set(0,someValue);
}

您做的一切都很好。此外,您可以删除
myMap.put(specificKey,doubleList)
,因为列表已经存在

在您的场景中发生这种情况的原因是,所有三个键都引用了您在填充
树映射时创建的
列表的同一个实例。更改代码以为每个键插入新列表以解决此问题:

myMap.put(specificKey1, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0))));
myMap.put(specificKey2, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0))));
myMap.put(specificKey3, new ArrayList<Double>(Collections.nCopies(3, Double.valueOf(0))));
...
if (myMap.containsKey(specificKey1){
    myMap.get(specificKey1).set(0, someValue);
}
myMap.put(specificKey1,新的ArrayList(Collections.nCopies(3,Double.valueOf(0)));
put(specificKey2,新的ArrayList(Collections.nCopies(3,Double.valueOf(0));
put(specificKey3,新的ArrayList(Collections.nCopies(3,Double.valueOf(0));
...
if(myMap.containsKey(specificKey1){
获取(specificKey1).set(0,someValue);
}

您已使用同一列表对象的三个实例填充地图。您需要创建三个不同的列表。例如:

TreeMap<String, List<Double>> myMap = new TreeMap<>();
myMap.put(specificKey,  Arrays.asList(0.0, 0.0, 0.0));
myMap.put(specificKey2, Arrays.asList(0.0, 0.0, 0.0));
myMap.put(specificKey3, Arrays.asList(0.0, 0.0, 0.0));
TreeMap myMap=newtreemap();
put(specificKey,Arrays.asList(0.0,0.0,0.0));
put(specificKey2,Arrays.asList(0.0,0.0,0.0));
put(specificKey3,Arrays.asList(0.0,0.0,0.0));

您已使用同一列表对象的三个实例填充地图。您需要创建三个不同的列表。例如:

TreeMap<String, List<Double>> myMap = new TreeMap<>();
myMap.put(specificKey,  Arrays.asList(0.0, 0.0, 0.0));
myMap.put(specificKey2, Arrays.asList(0.0, 0.0, 0.0));
myMap.put(specificKey3, Arrays.asList(0.0, 0.0, 0.0));
TreeMap myMap=newtreemap();
put(specificKey,Arrays.asList(0.0,0.0,0.0));
put(specificKey2,Arrays.asList(0.0,0.0,0.0));
put(specificKey3,Arrays.asList(0.0,0.0,0.0));