开发者

HashMap as a static member in java

I want to carry a HashMap over as a static member for each instance of a new class. Every time I try to .get or.put into my HashMap, however, I get a NullPointerException. Help!?

I'm doing: public class EmailAccount { private static HashMap<String,Integer> name_list; and then name_list.put(last_name, occ开发者_StackOverflowurences); Even name_list.containsKey(last_name); returns NullPointer.

This comes from an earlier question: Count occurrences of strings in Java


You need to instantiate it.

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

See also:

  • Java tutorial - Creating objects
  • Java collections tutorial - The Map interface

Note that using "list" in variable name of a map is confusing. Don't you want it to be a name_map or name_occurences? That underscore does by the way also not really fit in Java naming conventions, but that aside.


You still need to initialize it, like

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

When you leave a class-level object field with no initialization -- or any object reference, for that matter, it defaults to null.

While it may seem obvious to you that you want a HashMap, so it should just implicitly initialize it, Java doesn't know if you want in fact a HashMap, or maybe a HashMap subclass, like LinkedHashMap

Class-level primitives, like int can be left just like private static int someNumber; and won't throw a NullPointerException by accessing it--but that's because primitives can't be null. Java will assign it some default value (in int's case, 0).


You didn't instantiate the list. You declared it, but didn't instantiate.


You created a field that can hold a HashMap, but you didn't put anything inside of it

You need to put a new HashMap<String, Integer>() into your field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜