Help needed with Java HashMap

Revision en1, by dimriXD, 2019-07-01 11:05:07

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

Tags #java8, hashmap

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English dimriXD 2019-07-01 11:05:07 1139 Initial revision (published)