哈希码比较问题 [英] Hashcode comparison problem

查看:77
本文介绍了哈希码比较问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,在我们的例子中称为规则,该对象本身是字段列表,我必须对其进行哈希码比较,因为我们不能在 系统.

I have list of a an object which is termed as rule in our case, this object itself is a list of field for which I have to do hashcode comparison as we can't duplicate rule in the system.

i.e假设我有两个规则R1和R2,其中的字段A& B.

i.e Let say I have two Rules R1 and R2 with fields A & B.

现在,如果A&的值为R1中的B分别是7和2.

Now if values of A & B in R1 are 7 and 2 respectively.

在R2中分别为3和4,然后我使用了检查重复性的过程 哈希码比较的系统中的规则失败

And in R2 it's 3 and 4 respectively then the process I have used to check the duplicity of Rules in the system that is hashcode comparison fails

我使用的方法是

for(Rule rule : rules){
changeableAttrCode=0;

fieldCounter=1;

attributes = rule.getAttributes();

for(RuleField ruleField : attributes){

changeableAttrCode = changeableAttrCode + (fieldCounter * ruleField.getValue().hashCode());

fieldCounter++;

}
parameters = rule.getParameters();

for(RuleField ruleField : parameters){

changeableAttrCode = changeableAttrCode + (fieldCounter * ruleField.getValue().hashCode());

fieldCounter++;

}

changeableAttrCodes.add(changeableAttrCode);

在这里changeableAttrCodes中,我们存储了所有规则的哈希码.

here changeableAttrCodes where we store the hashcode of all the rules.

所以请提出更好的方法,这样将来就不会出现这种问题,并且可以看到系统规则的重复性.

so can please suggest me better method so that this kind of problem does not arise in future as well as duplicity of rules in system can be seen.

预先感谢

推荐答案

  • 在Rule类中实现hashCodeequals.
  • equals的实现必须比较其值.
    • Implement hashCode and equals in class Rule.
    • Implementation of equals has to compare its values.
    • 然后使用HashSet<Rule>并询问if(mySet.contains(newRule))

      HashSet +等于实现解决了哈希不唯一的问题.它使用散列进行分类和提高速度,但最后使用equals来确保具有相同散列的两个规则是否为同一规则.

      HashSet + equals implementation solves the problem of the non-uniqueness of the hash. It uses hash for classifying and speed but it uses equals at the end to ensure that two Rules with same hash are the same Rule or not.

      有关散列的更多信息:如果您想手工操作,请使用素数数字,然后在JDK代码中查看字符串散列码.如果您想进行干净的实现,请尝试检索元素的哈希码,创建某种类型的int数组,然后使用Arrays.hashCode(int [])来获取元素组合的哈希码.

      More on hash: if you want to do it by hand, use the prime number sudggestion, and review the JDK code for string hashcodes. If you want to make a clean implementation try to retrieve the hashcode of the elements, make some kind of array of ints and use Arrays.hashCode(int[]) to get a hashcode for the combination of them.

      这篇关于哈希码比较问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆