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;
}
}
This is a perfect hashing function because in the memory we have :
So in red, 5 bits
store the day (1 to 31), in yellow 4 bits
store the month (1 to 12) and the others store the year (1 to 16777215).
What's the benefit of a perfect hashFunction
? AFAIK, it can guaranted the add/remove/contains in O(1)
in an HashSet
but could I get other benefits of having one ?
I saw that many hash functions use prime numbers, what's the best manner to construct one (I imagine that create a perfect hashfunction is uncommun/rare) ?
EDIT :
About prime numbers -> answered here