HashMap作为java中的静态成员
我想为新类的每个实例保留一个 HashMap 作为静态成员。然而,每次我尝试 .get 或 .put 到我的 HashMap 中时,我都会收到 NullPointerException。帮助!?
我正在做:public class EmailAccount { 私有静态 HashMap
然后 name_list.put(last_name,occurrences);
甚至 name_list.containsKey(last_name);
返回 NullPointer。
这来自于之前的一个问题:计数 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 {
and then
private static HashMap<String,Integer> name_list;name_list.put(last_name, occurences);
Even name_list.containsKey(last_name);
returns NullPointer.
This comes from an earlier question: Count occurrences of strings in Java
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要实例化它。
另请参阅:
请注意,在 a 的变量名中使用“list”地图很混乱。您不希望它是
name_map
或name_occurrences
吗?顺便说一下,这个下划线也不太符合 Java 命名约定,但除此之外。You need to instantiate it.
See also:
Note that using "list" in variable name of a map is confusing. Don't you want it to be a
name_map
orname_occurences
? That underscore does by the way also not really fit in Java naming conventions, but that aside.您仍然需要初始化它,就像
当您离开没有初始化的类级对象字段或任何对象引用时,它默认为 null。
虽然对您来说您想要一个 HashMap 似乎是显而易见的,所以它应该只是隐式初始化它,但 Java 不知道您实际上是否想要一个 HashMap,或者可能是一个 HashMap 子类,例如 LinkedHashMap
类级基元,如
int
可以像private static int someNumber;
一样保留,并且不会通过访问它抛出 NullPointerException - 但那是因为基元不能为 null。 Java 将为它分配一些默认值(在int
的情况下为 0)。You still need to initialize it, like
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 likeprivate 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 (inint
's case, 0).您没有实例化该列表。您声明了它,但没有实例化。
You didn't instantiate the list. You declared it, but didn't instantiate.
您创建了一个可以容纳 HashMap 的字段,但没有在其中放入任何内容。
您需要将一个
new HashMap()
放入您的字段中。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.