0
$\begingroup$

Why is the initial value of hash 17 and not 0?

/**
 * Returns an integer hash code for this date.
 *
 * @return an integer hash code for this date
 */
@Override
public int hashCode() {
    int hash = 17;
    hash = 31*hash + month;
    hash = 31*hash + day;
    hash = 31*hash + year;
    return hash;
}

https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Date.java.html

$\endgroup$
1
$\begingroup$

There is no compelling reason that I'm aware of. The hash algorithm would also work about as well with an initial value of 0, as far as I can see.

$\endgroup$
1
  • $\begingroup$ You are right. The initial value doesn't matter. I tried changing it to 0 and got exactly the same number of collisions. Also, that hash function isn't very good because it "resets" every 31 years. A better hash function would be month + 12 * day + 12 * 31 * year $\endgroup$
    – Panic
    Nov 28 '19 at 2:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.