Java HashMap类抛出NullPointerException

时间:2017-07-19 19:31:40

标签: java nullpointerexception hashmap bluej

我正在使用BlueJ并测试HashMap类以了解它是如何工作的。下面是我用来测试该类的代码。在第一次尝试在构造函数中调用fillMyMap()方法时,第23行引发了一个错误。

我尝试删除构造函数中对fillMyMap()的调用。 HashMapTester对象是实例化的,但是当我显式调用该方法时,会抛出相同的NullPointerException

我尝试重写myMap变量声明,但使用不同的语法会导致编译失败。

我已经测试了其他HashMap代码(例如,来自Objects First with BlueJ),并且该代码运行正常,因此没有库,类或包问题。

我试着改变变量,以为我不小心碰到了一个保留字。同样的结果。这段代码有什么问题?

import java.util.HashMap;

public class HashMapTester
{
    //Fields
    public HashMap<String, String> myMap;

    // The constructor is supposed to construct a new
    // HashMap object with variable name myMap.
    // The fillMyMap() method call simply fills the HashMap
    // with data prior to testing it.
    public HashMapTester()
    {
        HashMap<String, String> myMap = new HashMap<String, String>();
        fillMyMap();
    }

    // fillMyMap() methods is supposed to fill up 
    // the keys and values of the HashMap<String, String> 
    // object.
    public void fillMyMap()
    {
        myMap.put("doe", "A deer...a female deer."); //<-- ERROR OCCURS HERE!
        myMap.put("ray", "A drop of golden sun.");
        myMap.put("me", "A name I call myself.");
        myMap.put("fah", "A long, long way to run.");
        myMap.put("sew", "A needle sewing thread.");
        myMap.put("la", "A note to follow sew.");
        myMap.put("tea", "It goes with jam and bread.");
    }

    public String sing(String note)
    {
        String song = myMap.get(note);    
        return song;
    }
}

5 个答案:

答案 0 :(得分:3)

HashMap<String, String> myMap = new HashMap<String, String>();

在构造函数中声明一个局部变量,而不是实例化字段变量。

使用

this.myMap = new HashMap<String, String>();

答案 1 :(得分:1)

您在构造函数中创建了一个局部变量。您没有初始化实例变量。

答案 2 :(得分:1)

这是因为你已经写过HashMap<String,String> myMap=new HashMap<String,String>();(对第一位有压力)。你在这里声明一个新的局部变量。

HashMapTester()函数应为:

public HashMapTester(){
  this.myMap=new HashMap<String,String>();
  fillMyMap();
}

答案 3 :(得分:1)

最短,最简单的修复。删除此:HashMap<String, String>

import java.util.HashMap;

public class HashMapTester {
    public HashMap<String, String> myMap;

    public HashMapTester(){
        myMap = new HashMap<String, String>();   //<-- I WAS THE ERROR
        fillMyMap();
    }

    public void fillMyMap() {
        myMap.put("doe", "A deer...a female deer."); //<--NO ERROR OCCURS HERE!
        myMap.put("ray", "A drop of golden sun.");
        myMap.put("me", "A name I call myself.");
        myMap.put("fah", "A long, long way to run.");
        myMap.put("sew", "A needle sewing thread.");
        myMap.put("la", "A note to follow sew.");
        myMap.put("tea", "It goes with jam and bread.");
    }

    public String sing(String note){
        String song = myMap.get(note);    
        return song;
    }
}

答案 4 :(得分:0)

在您的构造函数中,您正在使用

HashMap<String,String> myMap=new HashMap<String,String>();

何时应该使用

this.myMap = new HashMap<String, String>();

这是实例化字段变量的方式,而不仅仅是声明一个新的局部变量映射。

相关问题