X
    Categories: Java Core

Java hashCode() Method Example

The super class in Java java.lang.Object provides two important methods for comparing objects: equals() and hashcode(). These methods are widely used when faced against implementing an interaction between classes. In this tutorial, we are only going to look at hashCode().

Method Definition and Implementation

hashCode(): By default, this method returns a random integer that is unique every time. If you execute your application twice for example, the second time, the value would be different. hashCode value is mostly used in hashing formatted collections such as HashSet, HashMap, etc. Please note that this method must be overriden in every class which overrides equals() method. 

Simple illustration of hashCode

List of collections that can be used by hashCode()



When should we use hashCode() method

If we ever want to execute an equals() method, we need to make sure that these objects have the same unique hashcode ID. We should never execute equals() when the hashcode ID is different.

NOTE: When a hashCode() comparison returns false, the equals() method must also return false. If the hashcode is different, then the objects are not equal.

Practical example of hashCode() and equals()

import java.lang.*;
public class hashCodeExample {
    public static void main(String[] args){ 
        Car BMW = new Car(1, "BMW"); // 1 --> ID, 2 --> the name of the car brand
        Car mercedes = new Car(2, "Mercedes"); // 1 --> ID, 2 --> the name of the car brand
        
        boolean isHashcodeEqual = BMW.hashCode() == mercedes.hashCode();

        if (isHashcodeEqual) {
            System.out.println("Equal");
        } else {
            System.out.println("No need to compare with equals() method as it is clear " +
            "that the id of these objects is not equal.");
        }
    }

    static class Car {
        int id;
        String brand;

        public Car (int id, String brand) {
            this.id = id;
            this.brand = brand;
        }

        @Override
        public boolean equals(Object obj) {
            if(this == obj) {
                return true;
            }
            else if(obj == null || getClass() != obj.getClass()) {
                return false;
            }
            Car car = (Car) obj;
            return id == car.id && brand.equals(car.brand);
        }

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

Brief breakdown of the code above

The first couple of lines, we are creating two “Car” objects and passing an id and a brand name.

Car BMW = new Car(1, "BMW"); // 1 --> ID, 2 --> the name of the car brand
Car mercedes = new Car(2, "Mercedes"); // 1 --> ID, 2 --> the name of the car brand

Then we are storing a boolean value in a variable called isHashCodeEqual that gets either true or false depending upon whether the id of the two objects is equal.

boolean isHashcodeEqual = BMW.hashCode() == mercedes.hashCode();

Right after that, we have a condition that either checks if isHashCodeEqual true or false. If true, that means that the id of the two objects are equal. If not, that means otherwise. If they are equal, we simply print “Equal”. If not, we print a useful message that basically says, if they are not equal, there is no need of checking with equals as these two objects do not share the same id.

        if (isHashcodeEqual) {
            System.out.println("Equal");
        } else {
            System.out.println("No need to compare with equals() method as it is clear " +
            "that the id of these objects is not equal.");
        }

Then below is our static class “Car”.

   static class Car {
        int id;
        String brand;

        public Car (int id, String brand) {
            this.id = id;
            this.brand = brand;
        }

        @Override
        public boolean equals(Object obj) {
            if(this == obj) {
                return true;
            }
            else if(obj == null || getClass() != obj.getClass()) {
                return false;
            }
            Car audi = (Car) obj;
            return id == audi.id && brand.equals(audi.brand);
        }

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

Common Mistakes with hashCode()

  • Returning a constant value in the hashCode() method instead of returning a unique vale for each object.
  • Not overriding equals() and hashCode() when working with hash collections like HashMap.
  • Forgetting to override hashCode() with equals() method or the other way around.

Key things to remember about hashCode()

  1. Use an effective algorithm so a unique hashcode is generated
  2. When overriding the equals() method, always make sure you have overriden the hashCode() method as well.
  3. When the result of comparing two object’s hashcodes is false, the equals() method should also be false. (see the code example above)
  4. In the event of equals() and hashCode() being not overriden when suing hash collections, the collection will have duplicates.
4 1 vote
Article Rating
ym_coding:
Related Post