简体   繁体   中英

Why does this Hashmap Iteration not work? I get a NullPointer Exception

Map<String, String> listOfIndexes = INDEXED_TABLES.get(tableName);
Iterator it = listOfIndexes.entrySet().iterator();
while (it.hasNext()) { 
    Map.Entry pairs = (Map.Entry)it.next();
    System.out.println(pairs.getKey());
}

My Hashmap is like this :

public static  Map<String, Map<String, String>> INDEXED_TABLES = new HashMap<String, Map<String, String>>()
{{
    put("employee",  EMPLOYEE);
}};

public static  Map<String, String> EMPLOYEE = new HashMap<String, String>()
{{
    put("name", "Test");
    put("age", "Test");
    put("sex", "test");
}};

This is because you outsmarted yourself: your initializers depend on the order of execution. At the time this line runs

put("employee",  EMPLOYEE);

EMPLOYEE is still null , so that's what gets put into your Map<String,Map<String,String>> .

You can switch the order of initializers to fix this problem. However, you would be better if you put initialization code into a separate initializer, rather than using anonymous classes with custom initializers:

public static  Map<String, Map<String, String>> INDEXED_TABLES = new HashMap<String, Map<String, String>>();
public static  Map<String, String> EMPLOYEE = new HashMap<String, String>();
static {
    EMPLOYEE.put("name", "Test");
    EMPLOYEE.put("age", "Test");
    EMPLOYEE.put("sex", "test");
    INDEXED_TABLES.put("employee",  EMPLOYEE);
}

It looks like you are putting EMPLOYEE into the map before it has been initialized, so it will be null (and remain so, even if you assign something to EMPLOYEE later).

Reverse the order of the two statements.

Or, while in general I disapprove of the double-brace-initializer (hopefully, we'll get proper Collection literals in Java 8):

public static  Map<String, Map<String, String>> INDEXED_TABLES = 
  new HashMap<String, Map<String, String>>(){{
    put("employee",  new HashMap<String, String>(){{
      put("name", "Test");
      put("age", "Test");
      put("sex", "test");
   }}
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM