Create a HashMap with a fixed Key corresponding to a HashSet. point of departure

后端 未结 1 577
深忆病人
深忆病人 2021-01-16 04:54

My aim is to create a hashmap with a String as the key, and the entry values as a HashSet of Strings.


OUTPUT

This is what the output looks lik

1条回答
  •  囚心锁ツ
    2021-01-16 05:04

    I'm not clear from your question what isn't working, or if you're seeing actual errors. But, while your basic data structure idea (HashMap of String to Set) is sound, there's a bug in the "add" function.

    public static HashSet put_to_hash(String key, String value) 
    {
        if (!q_valMap.containsKey(key)) 
        {
            return q_valMap.put(key, new HashSet() );
        }
        HashSet list = q_valMap.get(key);
        list.add(value);
        return q_valMap.put(key, list);
    }
    

    In the case where a key is seen for the first time (if (!q_valMap.containsKey(key))), it vivifies a new HashSet for that key, but it doesn't add value to it before returning. (And the returned value is the old value for that key, so it'll be null.) So you're going to be losing one of the Q-values for every term.

    For multi-layered data structures like this, I usually special-case just the vivification of the intermediate structure, and then do the adding and return in a single code path. I think this would fix it. (I'm also going to call it valSet because it's a set and not a list. And there's no need to re-add the set to the map each time; it's a reference type and gets added the first time you encounter that key.)

    public static HashSet put_to_hash(String key, String value) 
    {
        if (!q_valMap.containsKey(key)) {
            q_valMap.put(key, new HashSet());
        } 
        HashSet valSet = q_valMap.get(key);
        valSet.add(value);
        return valSet;
    }
    

    Also be aware that the Set you return is a reference to the live Set for that key, so you need to be careful about modifying it in callers, and if you're doing multithreading you're going to have concurrent access issues.

    Or just use a Guava Multimap so you don't have to worry about writing the implementation yourself.

    0 讨论(0)
提交回复
热议问题