I found this program in my tutorial, which basically takes into account the appearance of each row in the String tst array.
public class Test { private static HashMap<String, Integer> mp = new HashMap<String, Integer>(); public static void main(String[] args) { String[] tst = new String[] { "ABC", "DEF", "DEF", "DEF","ABC", "DEF", "ABC" }; checkMap(tst); } public static void checkMap(String[] str) { for (String st : str) { if (!mp.containsKey(st)) { mp.put(st, 1); } else { Integer ct = mp.get(st); if(ct!=null) { ct++; mp.put(st, ct); } } } for (Map.Entry<String, Integer> entry : mp.entrySet()) { System.out.println(entry.getKey() + " ocurrs " + entry.getValue()+ " times"); } }
}
The output for the code is
ABC ocurrs 3 times DEF ocurrs 4 times
My question here in the if / else statement is -
if (!mp.containsKey(st)) { mp.put(st, 1); } else { Integer ct = mp.get(st); if(ct!=null) { ct++; mp.put(st, ct); } }
When we do not put any entries inside the hash map (the hashmap is empty), on what basis does it work? Sorry if this is a very simple question, but I have not found an answer anywhere on the Internet that explains this. I am confused by what is written in the if / else loop. Also, this line here is -
Integer ct = mp.get(st);
How can we get the value the key is mapped to when the infact hashmap is actually empty? I am trying to associate this with an array. If you request the elements of an array after its creation, but are not initialized, it returns a null pointer. Someone please explain how this works for a hash map. Once again, we apologize for asking this basic question.
user2341013
source share