在 Java 中覆盖 hashCode() [英] Overriding hashCode() in Java

查看:95
本文介绍了在 Java 中覆盖 hashCode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个书"类:

public class Book {

public static int idCount = 1;

private int id;
private String title;
private String author;
private String publisher;
private int yearOfPublication;
private int numOfPages;
private Cover cover;

...

}

然后我需要覆盖 hashCode() 和 equals() 方法.

And then i need to override the hashCode() and equals() methods.

@Override
public int hashCode() {

    int result = id; // !!!

    result = 31 * result + (title != null ? title.hashCode() : 0);
    result = 31 * result + (author != null ? author.hashCode() : 0);
    result = 31 * result + (publisher != null ? publisher.hashCode() : 0);
    result = 31 * result + yearOfPublication;
    result = 31 * result + numOfPages;
    result = 31 * result + (cover != null ? cover.hashCode() : 0);

    return result;
}

equals() 没问题.我只是想知道 hashCode() 方法中的一件事.

It's no problem with equals(). I just wondering about one thing in hashCode() method.

注意:IntelliJ IDEA 生成了 hashCode() 方法.

那么,可以将结果变量设置为 id,还是应该使用一些质数?

这里有什么更好的选择?

What is the better choice here?

谢谢!

推荐答案

请注意,只有结果的初始值设置为 id,而不是最后一个.最终值是通过将该初始值与对象其他部分的哈希码相结合,乘以一个小素数(即 31)的幂来计算的.在这种情况下,使用 id 而不是任意素数绝对是正确的.

Note that only the initial value of the result is set to id, not the final one. The final value is calculated by combining that initial value with hash codes of other parts of the object, multiplied by a power of a small prime number (i.e. 31). Using id rather than an arbitrary prime is definitely right in this context.

一般来说,散列码是素数没有优势(需要是素数的散列桶的数量).使用 int 作为它自己的哈希码(在您的情况下,即 idnumOfPages)是一种有效的方法.

In general, there is no advantage to hash code being prime (it's the number of hash buckets that needs to be prime). Using an int as its own hash code (in your case, that's id and numOfPages) is a valid approach.

这篇关于在 Java 中覆盖 hashCode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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