hashCode Method in Java

For every Object in Java, a unique no is generated by JVM which is known as hashCode. JVM used this hashCode while saving Objects into hash-based data structures like HashMap, HashTable, and HashSet.The main advantage of saving objects based on hash-based data structure is searching becomes easy(hashing is the most powerful search algorithm at present time.

If we use hashCode() of Object class then it will generate hash code based on address of the object. We can also override hashCode() according our requirment.

Note- hashCode does not represent address of object.

  • Overriding hashCode() is said to be proper if and only if it generate unique number as hashCode for every object.
public class HashCodeExample {
     private int i;
    @Override
    public int hashCode() {
        return 10;
    }
}

The above hashCode() overriding is improper because for every object it will generate same number as hash.

public class HashCodeExample {
     private int i;

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

The above hashCode() overriding is proper because for every object it will generate different number as hashCode.

toString() vs hashCode()

  • If we are using toString() then it will internally call hashCode().
  • If we overriding toString() then overrided toString() may not call hashCode().

Similar Java Tutorials

3 thoughts on “hashCode Method in Java”

Leave a Comment