0

I created a TreeMap> and set arraylist values(0,0) for all Keys.Then I updated only single key value. But It ends up updating all Key values. Here is my simplified code

import java.util.*;

public class Test {
    public static void main(String[] args) {
        TreeMap<String, ArrayList<Integer>> treeMap = new TreeMap<>();
        String[] moduleList = {"apple", "orange", "grape"};
        ArrayList<Integer> emptyInitialArrayList = new ArrayList<>(Arrays.asList(0, 0));
        for (String tempModule : moduleList) {
            treeMap.put(tempModule, emptyInitialArrayList);
        }
        ArrayList<Integer> tempModuleMap = treeMap.get("apple");
        tempModuleMap.set(0, tempModuleMap.get(0) + 1);
        for (Map.Entry<String, ArrayList<Integer>> test : treeMap.entrySet()) {
            System.out.println(test.getKey());
            System.out.println(test.getValue().get(0));
            System.out.println(test.getValue().get(1));
        }
    }
}

Output for this code:

apple
1
0
grape
1
0
orange
1
0

I am missing something. Cannot find where I am doing the mistake.

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
Harish Raj
  • 27
  • 4
  • 2
    Same `emptyInitialArrayList` object is shared by all three keys. – tsolakp Nov 07 '18 at 16:43
  • The duplicate is about adding the same object repeatedly to a list. Your problem is caused by adding the same object (a list) repeatedly to a map. It's the same problem, but don't confused your list with the dup's list. It's you map that's similar to dup's list. – Andreas Nov 07 '18 at 17:04

2 Answers2

3

To fix, just put the new ArrayList call in the loop. Otherwise, you are sharing the same value object across all of the keys

    String[] moduleList = {"apple", "orange", "grape"};
    for (String tempModule : moduleList) {
        ArrayList<Integer> emptyInitialArrayList = new ArrayList<>(Arrays.asList(0, 0));
        treeMap.put(tempModule, emptyInitialArrayList);
    }
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

You have to add a new empty initial array list for each temp module.

  for (String tempModule : moduleList) {
        ArrayList<Integer> emptyInitialArrayList = new ArrayList<>(Arrays.asList(0, 0));
        treeMap.put(tempModule, emptyInitialArrayList);
    }

Your code currently puts the same array list instance for each key in the map. So when you later update it for the apple key, the change applies to the other keys as well.

Pietro Boido
  • 186
  • 5