我在以下代码中收到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 :(得分:4)
您必须初始化地图:
private Map<String,List<Entry>> Days = new HashMap<>();
请注意,您可以使用
List<Entry> entries = new ArrayList <Entry> ();
并添加到地图中,而不是添加空。
当应用程序在需要对象的情况下尝试使用null时抛出。其中包括:
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.
由于您在执行此操作时未初始化Map对象:
Days.put(dw.toString().toLowerCase(),entries);
你得到NullPointerException,因为你是“访问或修改空对象的字段。”。
答案 1 :(得分:2)
private Map<String,List<Entry>> Days;
Days
未初始化。将其更改为
private Map<String,List<Entry>> Days = new HashMap<>();
或以另一种方式初始化。
正如JavaDoc所述,null
HashMap
个键和值
另请注意,在您的代码中没有空列表,根本没有列表。