2463. Java Advanced - hashCode() in Java - Draft
hashCode


Create concurrent application with threadings.

1. Understanding How hashCode() Works

Simply put, hashCode() returns an integer value, generated by a hashing algorithm.

Objects that are equal (according to their equals()) must return the same hash code. It’s not required for different objects to return different hash codes.

The general contract of hashCode() states:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, hashCode() must consistently return the same value, provided no information used in equals comparisons on the object is modified. This value needs 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 value
  • 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, developers should be aware that producing distinct integer results for unequal objects improves the performance of hash tables

2. Hash Function

2.1 Naive hashCode() Implementation

@Override
public int hashCode() {
    return 1;
}

2.2 Improved hashCode() Implementation

@Override
public int hashCode() {
    return (int) id * name.hashCode() * email.hashCode();
}

2.3 Standard hashCode() Implementations

@Override
public int hashCode() {
    int hash = 7;
    hash = 31 * hash + (int) id;
    hash = 31 * hash + (name == null ? 0 : name.hashCode());
    hash = 31 * hash + (email == null ? 0 : email.hashCode());
    return hash;
}

3. Hash Collisions

5. References