Java: Composite key in hashmaps

前端 未结 9 681
太阳男子
太阳男子 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

    You could have a custom object containing the two strings:

    class StringKey {
        private String str1;
        private String str2;
    }
    

    Problem is, you need to determine the equality test and the hash code for two such objects.

    Equality could be the match on both strings and the hashcode could be the hashcode of the concatenated members (this is debatable):

    class StringKey {
        private String str1;
        private String str2;
    
        @Override
        public boolean equals(Object obj) {
            if(obj != null && obj instanceof StringKey) {
                StringKey s = (StringKey)obj;
                return str1.equals(s.str1) && str2.equals(s.str2);
            }
            return false;
        }
    
        @Override
        public int hashCode() {
            return (str1 + str2).hashCode();
        }
    }
    

提交回复
热议问题