返回嵌套散列映射
我有以下两种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()
,也得到了同样的错误。
hashMapTemp.putAll(finalHashMap.get('j'));
我想这应该是:
hashMapTemp.putAll(finalHashMap.get("j"));
你在finalHashMap
键是一个字符串,而不是一个字符。
hashMapTemp.putAll(finalHashMap.get('j'));
这条线有点奇怪,你寻找一个字符而不是字符串(如你所定义的)。 考虑使用static HashMap<Character, Student> finalHashMap = new HashMap<>()
public static HashMap<String, Student> find(String key, HashMap<String, HashMap<String, Student>> dataMap) {
HashMap<String, Student> result = null;
for (String s : dataMap.keySet()) {
if (s.equalsIgnoreCase(key)) {
result = dataMap.get(s);
break;
}
}
return result;
}
然后只需要调用像这样的方法:
HashMap<String, Student> result = find("j", finalHashMap);
使用HashMap的一个要点是什么?它提供了一种O(1)查找方法,如果要找到一个基于某个键的值,在所有键上进行迭代,直到找到所需的一个键,使其成为O(n)? – 2014-10-05 17:29:24
你在哪里得到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