Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good hashCode for a year and month tuple in java

In Java, let's say I have a long list of Year and Month pairs. Like 2018:03 with a lot of duplicates.

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

I want to loop over this list and create a hash from those two values for every entry, to determine if I already have a specific combination.

Usually I would create an Object for such an entry, with two int members and override equals and hashcode, adding them all into a Set.

How should I implement the hashCode?

As far as I remember from effective java, I would write the something like:

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

But I think, because month will always be lesser than year, in this case I am good with:

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

until the year 4020, there should not occur any collision.

Are there any more effective ways to achieve my goal, you can think of? Or is it too late already and my head is falling apart?

like image 489
JacksOnF1re Avatar asked Dec 11 '25 08:12

JacksOnF1re


1 Answers

As long as it satisfies the general contract of hashCode, it should be a fine hash code implementation:

  • 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.

Another approach to implement the hashCode method would be to call Objects.hash:

return Objects.hash(year, month);
like image 115
Sweeper Avatar answered Dec 13 '25 20:12

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!