Java:哈希图中的复合键 [英] Java: Composite key in hashmaps
本文介绍了Java:哈希图中的复合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一组对象存储在hashmap中,其中键应是两个字符串值的组合.有没有办法做到这一点?
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 concatenate the two strings , but im sure there is a better way to do this.
推荐答案
您可以有一个包含两个字符串的自定义对象:
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();
}
}
这篇关于Java:哈希图中的复合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文