HashMap as a static member in java

I want to pass the HashMap as a static member for each instance of the new class. However, every time I try to execute .get or.put in my HashMap, I get a NullPointerException. Help!

I do: public class EmailAccount { private static HashMap<String,Integer> name_list;and then name_list.put(last_name, occurences);Even name_list.containsKey(last_name);returns NullPointer.

This is related to an earlier question: Count string occurrences in Java

+3
source share
4 answers

You need to create an instance.

private static Map<String, Integer> name_list = new HashMap<String, Integer>();

See also:


, "" . , name_map name_occurences? , , Java, .

+9

,

private static HashMap<String, Integer> name_list = new HashMap<String, Integer>();

- , null.

, HashMap, , Java , HashMap , , HashMap, LinkedHashMap

, int, , private static int someNumber; NullPointerException, , , . Java ( int case, 0).

+5

You have not created an instance of the list. You declared this, but did not create an instance.

+2
source

You created a field that may contain a HashMap, but you didn’t put anything into it

You need to put new HashMap<String, Integer>()in your box.

+1
source

Source: https://habr.com/ru/post/1787342/


All Articles