1 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
它應(yīng)該是:
public static final Map<String, Month> months = new HashMap<String, Month>() {{
put("Jan", Month.January);
put("Feb", Month.February);
put("Mar", Month.March);
put("Apr", Month.April);
put("Jun", Month.June);
put("Jul", Month.July);
put("Aug", Month.August);
put("Sep", Month.September);
put("Oct", Month.October);
put("Nov", Month.November);
put("Dec", Month.December);
}};
months.put()導(dǎo)致NullPointerException,因?yàn)閳?zhí)行語(yǔ)句時(shí)static變量months仍然存在。nullput
作為替代方案,避免創(chuàng)建匿名類實(shí)例,而是編寫:
public static final Map<String, Month> months = new HashMap<String, Month>();
static {
months.put("Jan", Month.January);
months.put("Feb", Month.February);
months.put("Mar", Month.March);
months.put("Apr", Month.April);
months.put("Jun", Month.June);
months.put("Jul", Month.July);
months.put("Aug", Month.August);
months.put("Sep", Month.September);
months.put("Oct", Month.October);
months.put("Nov", Month.November);
months.put("Dec", Month.December);
}
添加回答
舉報(bào)