2

我在以下代码中得到 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;

但是如何创建一个空列表并将其添加到地图中?

4

2 回答 2

5

您必须初始化地图:

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

请注意,您可以使用

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

并添加到地图中,而不是添加空值。

关于NullPointerException

当应用程序在需要对象的情况下尝试使用 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 因为你正在“访问或修改空对象的字段。”。

于 2012-11-23T18:35:44.850 回答
3
private Map<String,List<Entry>> Days;

Days未初始化。将其更改为

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

或以另一种方式初始化它。

正如JavaDoc所述,null键和值允许在HashMap

另请注意,在您的代码中没有空列表,根本没有列表。

于 2012-11-23T18:37:11.717 回答