Java: Composite key in hashmaps

前端 未结 9 686
太阳男子
太阳男子 2020-12-24 12:53

I would like to store a group of objects in a hashmap , where the key shall be a composite of two string values. is there a way to achieve this?

i can simply concate

9条回答
  •  甜味超标
    2020-12-24 13:36

    public int hashCode() {
        return (str1 + str2).hashCode();
    }
    

    This seems to be a terrible way to generate the hashCode: Creating a new string instance every time the hash code is computed is terrible! (Even generating the string instance once and caching the result is poor practice.)

    There are a lot of suggestions here:

    How do I calculate a good hash code for a list of strings?

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        for ( String s : strings ) {
            result = result * prime + s.hashCode();
        }
        return result;
    }
    

    For a pair of strings, that becomes:

    return string1.hashCode() * 31 + string2.hashCode();
    

    That is a very basic implementation. Lots of advice through the link to suggest better tuned strategies.

提交回复
热议问题