Consider this class :
public final class MyDate {
private int year, month, day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
//Some stuff
@Override
public int hashCode() {
return ((year << 4) | month) << 5 | day;
}
}
这是一个完美的哈希函数,因为在内存中我们有:
所以在红色部分,5位
存储日(1到31),在黄色部分,4位
存储月份(1到12),其余部分存储年份(1到16777215)。
完美的hashFunction
的好处是什么?据我所知,在HashSet
中,它可以保证O(1)
的添加/删除/包含操作,但我还能从中获得其他好处吗?
我看到许多哈希函数使用质数,构建哈希函数的最佳方法是什么(我想创建一个完美的哈希函数是不常见/罕见的)?
编辑: