簡體   English   中英

返回嵌套的哈希圖

[英]Returning a nested hashmap

我有以下兩個HashMaps ,其中Student是我創建的對象,其格式為Student(String, String)

static HashMap<String, Student> hashMap = new HashMap<>();
static HashMap<String, HashMap<String, Student>> finalHashMap = new HashMap<>();

我創建了以下Students ,並將其添加到具有firstName作為Key hashMap

Student st1 = new Student("julian", "rogers");
Student st2 = new Student("jason", "Smith");

hashMap.put("julian", st1);
hashMap.put("jason", st2);

然后我將firstName的第一個字母作為keyhashMap添加到finalHashMap

finalHashMap.put("j", hashMap);

如何使用鍵j返回哈希圖?

我嘗試創建一個新的哈希表並使用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));
}

OUTPUT

 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM