我有以下两种HashMaps
其中Student
是我创建的对象,并且具有Student(String, String)
返回嵌套散列映射
static HashMap<String, Student> hashMap = new HashMap<>();
static HashMap<String, HashMap<String, Student>> finalHashMap = new HashMap<>();
我创建了以下Students
,并将它们加入到hashMap
与firstName
作为Key
Student st1 = new Student("julian", "rogers");
Student st2 = new Student("jason", "Smith");
hashMap.put("julian", st1);
hashMap.put("jason", st2);
然后我加hashMap
到finalHashMap
的第一个字母firstName
作为key
finalHashMap.put("j", hashMap);
我怎样才能返回与关键j
HashMap的?
我试着创建一个新的hashmap并使用get()
但它没有工作。我得到一个null pointer exception
static HashMap<String, Student> hashMapTemp = new HashMap<>();
hashMapTemp.putAll(finalHashMap.get('j'));
for (String key : hashMapTemp.keySet())
{
System.out.println(key + " " + hashMapTemp.get(key));
}
输出
java.lang.NullPointerException
at java.util.HashMap.putAll(Unknown Source)
注:我尝试使用put()
,也得到了同样的错误。
你在哪里得到NPE? – 2014-10-05 17:15:56
为什么你将结果添加到'hashMapTemp'而不是只是说'for(String key:finalHashMap.get(“j”))'? – Krease 2014-10-05 17:18:24
作为一个说明,如果将它作为一个自包含的类来演示问题而不是一堆代码片段,将来可能更容易解析这样的事情。 – Krease 2014-10-05 17:19:54