2012-11-23 32 views
1

,我在下面的代碼獲得NullPointerException異常:添加空單映射

private Map<String,List<Entry>> Days; 
private void intializeDays() { 
    //Iterate over the DayOfWeek enum and put the keys in Map 
    for(DayOfWeek dw : EnumSet.range(DayOfWeek.MONDAY,DayOfWeek.SUNDAY)){ 
    List<Entry> entries = null; 
    Days.put(dw.toString().toLowerCase(),entries); 
    } 
} 

我認爲它是因爲

List<Entry> entries = null; 

但後來如何創建一個空的列表,並把它添加到地圖?

+0

問題在於天映射。試試這個Days = new HashMap >(); – Addict

回答

4

您必須初始化您的地圖:

private Map<String,List<Entry>> Days = new HashMap<>(); 

注意,您可以使用

List<Entry> entries = new ArrayList <Entry>(); 

,並添加,而不是添加一個空的地圖。

關於NullPointerException

當應用程序試圖在需要的對象的情況下,使用空拋出該異常。這些措施包括:

Calling the instance method of a null object. 
Accessing or modifying the field of a null object. 
Taking the length of null as if it were an array. 
Accessing or modifying the slots of null as if it were an array. 
Throwing null as if it were a Throwable value. 
Applications should throw instances of this class to indicate other illegal uses of the null object. 

既然你沒有初始化您的地圖對象,當你這樣做:「訪問或修改null對象的字段」

Days.put(dw.toString().toLowerCase(),entries); 

您得到NullPointerException異常,因爲你。

2
private Map<String,List<Entry>> Days; 

Days未初始化。將其更改爲

private Map<String,List<Entry>> Days = new HashMap<>(); 

或者以另一種方式初始化它。

隨着JavaDoc狀態,null鍵和值被允許在HashMap

還要注意,在你的代碼有沒有空列表,沒有名單的。