dimriXD's blog

By dimriXD, history, 5 years ago, In English

I am trying to create a HashMap of Integer and another HashMap(Chracter, Integer)

The code is below:

Your code here...

public static void createHM(HashMap<Integer, HashMap<Character, Integer>> hm, char s[], int n) {
    	HashMap<Character, Integer> chm = new HashMap<>();
        for(int i = 0; i < n; i++) {
                if(chm.containsKey(s[i])) {
                    chm.put(s[i], chm.get(s[i])+1);
                } else {
                    chm.put(s[i], 1);
                }
            hm.put(i+1, chm);
        }
    }

Description: chm stands for current HashMap, I am trying to add hashmap created while iterating over char array "s" to be included in the the hm i.e. main HashMap as values while key to be the current iteration (i+1)

Problem: hm the main HashMap contains same hashMap as value for all keys and the hashMap value is equal to what supposed to be only for the final key i.e. n while iterating over char array "s" but all keys from 1 till n has same value

I hope I clarified the problem, please help what is the issue with this approach

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

The thing is that all chm maps (Maps of type <Character, Integer>) in each entry inside the hm map, are referring to the same map in memory, which is HashMap<Character, Integer> chm = new HashMap<>();.

So, at every step, all what you are doing is simply creating a new entry in the hm map, that has some integer as the key, and the value is just referring to the place where chm is stored in memory.

This means, at the end of the for loop, all the maps in the entries of the hm map, will just get their values from the same source, and therefore have the same value.

To fix this, every time, you are making a new entry in the hm map, you can create a new map of type <Character, Integer>, then copy all the values in the hm to that new map, and put the new map as the value in the entry of the hm map.

You can check this for better understanding: https://www.geeksforgeeks.org/passing-and-returning-objects-in-java/

Hope this helps