drawnitsud
drawnitsud

Reputation: 65

List.set replacing all indexes inside TreeMap

I have a TreeMap<String, List<Double> that I would like to pull out the List at a certain key, add a value at a certain index and then put it back into the TreeMap.

At the time of the below code, the TreeMap contains:

{specificKey=[0,0,0], specificKey2=[0,0,0], specificKey3=[0,0,0]}

I want to add the value to specificKey at index 0, so {specificKey=[777,0,0], specificKey2=[0,0,0], specificKey3=[0,0,0]}

Here is the offending code...

if (myMap.containsKey(specificKey){
    List<Double> doubleList = myMap.get(specificKey);
    doubleList.set(0, someValue);
    myMap.put(specificKey, doubleList);
}

Instead, what happens is: {specificKey=[777,0,0], specificKey2=[777,0,0], specificKey3=[777,0,0]}

Why is this happening when I am pulling out the exact List with myMap.get(specificKey)? And any ideas on how to accomplish what I need?

Upvotes: 1

Views: 55

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

You are doing everything right. Moreover, you can remove myMap.put(specificKey, doubleList), because the list is already there.

The reason why this happens in your scenario is that all three keys refer to the same instance of List<Double> that you created when populating your TreeMap. Change the code to insert new lists for each key to fix this problem:

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);
}

Upvotes: 3

Michael
Michael

Reputation: 44150

You have populated the map with three instances of the same list object. You need to create three distinct lists. For example:

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));

Upvotes: 2

Related Questions