hof*_*fmn 2 java hash overriding
我创建了一个类"Book":
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;
...
}
Run Code Online (Sandbox Code Playgroud)
然后我需要覆盖hashCode()和equals()方法.
@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;
}
Run Code Online (Sandbox Code Playgroud)
equals()没问题.我只是想知道hashCode()方法中的一件事.
注意:IntelliJ IDEA生成了hashCode()方法.
那么,将结果变量设置为id是否可以,或者我应该使用一些素数?
这里有什么更好的选择?
谢谢!
请注意,只有结果的初始值设置为id,而不是最后一个.通过将该初始值与对象的其他部分的哈希码组合,乘以小素数(即31)的幂来计算最终值.id在这种情况下,使用而不是任意素数肯定是正确的.
通常,哈希代码是素数没有优势(它是需要素数的哈希桶的数量).使用intas作为自己的哈希码(在你的情况下,那是id和numOfPages)是一种有效的方法.