gpt4 book ai didi

java - 什么是 java 中年和月元组的好 hashCode

转载 作者:行者123 更新时间:2023-11-29 06:50:42 25 4
gpt4 key购买 nike

在 Java 中,假设我有一长串 Year 和 Month 对。像 2018:03 有很多重复。

Month will always be starting with 1.
Year will always be > Month, starting with 2010
if Month or Year == 0 [not_set], hashcode can return 0 (fine), I ignore them

我想遍历此列表并根据每个条目的这两个值创建一个散列,以确定我是否已有特定组合。

通常我会为这样的条目创建一个对象,它有两个 int 成员并覆盖 equals 和 hashcode,将它们全部添加到一个 Set 中。

我应该如何实现哈希码?

据我对有效 java 的内存,我会写这样的东西:

@Override
public int hashCode() {
int hash = year;
hash = 31 * hash + month;
return hash;
}

但我认为,因为月份总是小于年份,在这种情况下我擅长:

@Override
public int hashCode() {
return year * month;
}

到 4020 年,应该不会发生任何碰撞。

有没有更有效的方法来实现我的目标,你能想到吗?还是已经太晚了,我的脑袋快要崩溃了?

最佳答案

只要满足the general contract即可hashCode的,应该是一个很好的哈希码实现:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

另一种实现 hashCode 方法的方法是调用 Objects.hash:

return Objects.hash(year, month);

关于java - 什么是 java 中年和月元组的好 hashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com