我正在使用BlueJ並測試HashMap類來查看它是如何工作的。以下是我用來測試課程的代碼。第一次嘗試在構造函數中調用fillMyMap()
方法時,會在第23行中引發錯誤。Java HashMap類拋出一個NullPointerException
我試着在構造函數中刪除對fillMyMap()
的調用。 HashMapTester對象被實例化,但當我明確調用該方法時拋出相同的NullPointerException
。
我試着重寫myMap
變量聲明,但使用不同的語法會導致編譯失敗。我已經測試了其他HashMap
代碼(例如,來自Objects First with BlueJ),並且代碼運行良好,所以沒有Library,Class或Package問題。
我試着改變變量,以爲我不小心碰到了一個保留字。結果相同。這段代碼有什麼問題?
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;
}
}
謝謝!現在完美運作。 – Andy
我也可以通過刪除'this'關鍵字來解決問題。 – Andy
是的,在這種情況下這不是必需的。只需要消除名稱的歧義。例如,假設構造函數也有一個名爲'myMap'的參數。 'this.myMap'指的是類字段,只是'myMap'指的是參數。因爲在你的例子中只有一個名爲'myMap'的變量,這不是必需的 –