为自定义类生成hashCode() [英] Generating hashCode() for a custom class

查看:249
本文介绍了为自定义类生成hashCode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Dish的类,并且在ArrayList s内部处理它 所以我不得不重写默认的hashCode()方法.

I have a class named Dish and I handle it inside ArrayLists So I had to override default hashCode() method.

@Override
public int hashCode() {
    int hash =7;
    hash = 3*hash + this.getId();
    hash = 3*hash + this.getQuantity();
    return hash;
}

当我得到两个带有id=4quan=3id=5quan=0hashCode()的盘子时,都是相同的;

When I get two dishes with id=4,quan=3 and id=5,quan=0, hashCode() for both is same;

((7*3)+4)*3+3 = 78
((7*3)+5)*3+0 = 78

我做错了什么?还是我选择的魔术数字7和3是错误的?

What am I doing wrong? Or the magic numbers 7 and 3 I have chosen is wrong?

如何正确覆盖hashCode(),以便生成唯一的哈希?

How do I properly override hashCode() so that it generates unique hashes?

PS :根据我从Google和SO搜索的内容,人们使用不同的数字,但使用的方法相同.如果问题出在数字上,那么我该如何明智地选择实际上不会增加​​乘法成本的数字,同时即使对于更多数量的属性也能很好地工作.

PS: From what I searched from google and SO, people use different numbers but the same method. If the problem is with the numbers, how do I wisely choose numbers that doesn't actually increase the cost for multiplication and at the same time works well even for more number of attributes.

说我有7个int属性,而我的第二个魔法没有.是31,最后的哈希将是第一个魔术编号. * 27512614111 ,即使我所有的属性都为0.所以我怎么做而没有使我的哈希值达到十亿,以保持处理器负担-免费?

Say I had 7 int attributes and my second magic no. is 31, the final hash will be first magic no. * 27512614111 even if all my attributes are 0. So how do I do it without having my hashed value in billions so as keep my processor burden-free?

推荐答案

这完全可以.散列函数不应具有普遍的唯一性,它只是给出一个提示,提示可能的哪些元素相等,应通过调用equals()对其进行更深入的检查.

This is perfectly OK. The hashing function is not supposed to be universally unique - it just gives a quick hint about which elements might be equal and should be checked in more depth by a call to equals().

这篇关于为自定义类生成hashCode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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