July 08, 2024

JaiHoDevs

Write a Java Program to Implement Hashcode and Equals

Program:

Write a Java Program to Implement Hashcode and Equals?

Description:

The hashcode of a Java Object is simply a number, it is 32-bit signed int, that allows an object to be managed by a hash-based data structure. We know that hash code is an unique id number allocated to an object by JVM. But actually speaking, Hash code is not an unique number for an object. If two objects are equals then these two objects should return same hash code. So we have to implement hashcode() method of a class in such way that if two objects are equals, ie compared by equal() method of that class, then those two objects must return same hash code. If you are overriding hashCode you need to override equals method also.

The below example shows how to override equals and hashcode methods. The class Price overrides equals and hashcode. If you notice the hashcode implementation, it always generates unique hashcode for each object based on their state, ie if the object state is same, then you will get same hashcode. A HashMap is used in the example to store Price objects as keys. It shows though we generate different objects, but if state is same, still we can use this as key.

Code:

package com.java2novice.algos;

import java.util.HashMap;

public class MyHashcodeImpl {

    public static void main(String a[]){
        
        HashMap<Price, String> hm = new HashMap<Price, String>();
        hm.put(new Price("Banana", 20), "Banana");
        hm.put(new Price("Apple", 40), "Apple");
        hm.put(new Price("Orange", 30), "Orange");
        //creating new object to use as key to get value
        Price key = new Price("Banana", 20);
        System.out.println("Hashcode of the key: "+key.hashCode());
        System.out.println("Value from map: "+hm.get(key));
    }
}

class Price{
    
    private String item;
    private int price;
    
    public Price(String itm, int pr){
        this.item = itm;
        this.price = pr;
    }
    
    public int hashCode(){
        System.out.println("In hashcode");
        int hashcode = 0;
        hashcode = price*20;
        hashcode += item.hashCode();
        return hashcode;
    }
    
    public boolean equals(Object obj){
        System.out.println("In equals");
        if (obj instanceof Price) {
            Price pp = (Price) obj;
            return (pp.item.equals(this.item) && pp.price == this.price);
        } else {
            return false;
        }
    }
    
    public String getItem() {
        return item;
    }
    public void setItem(String item) {
        this.item = item;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    
    public String toString(){
        return "item: "+item+"  price: "+price;
    }
}

Output:

In hashcode
In hashcode
In hashcode
In hashcode
Hashcode of the key: 1982479637
In hashcode
In equals
Value from map: Banana

In Java, implementing hashCode and equals methods is crucial when you are working with objects in collections like HashSet, HashMap, etc. Below is an example of a Java program that demonstrates how to implement these methods:

Example Class: Person

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Person person = (Person) obj;
        return age == person.age && name.equals(person.name);
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }

    public static void main(String[] args) {
        Person person1 = new Person("John", 25);
        Person person2 = new Person("John", 25);
        Person person3 = new Person("Jane", 30);

        // Test equals method
        System.out.println("person1 equals person2: " + person1.equals(person2)); // true
        System.out.println("person1 equals person3: " + person1.equals(person3)); // false

        // Test hashCode method
        System.out.println("person1 hashCode: " + person1.hashCode());
        System.out.println("person2 hashCode: " + person2.hashCode());
        System.out.println("person3 hashCode: " + person3.hashCode());

        // Use in HashSet
        Set<Person> set = new HashSet<>();
        set.add(person1);
        set.add(person2);
        set.add(person3);

        System.out.println("HashSet contains: " + set);
    }
}

Explanation:

  1. Person Class Definition: A simple Person class with name and age properties.
  2. Constructor: Initializes the name and age of the Person.
  3. Getter Methods: Methods to access the name and age properties.
  4. equals Method:
    • Checks if the current object is the same as the object passed as an argument.
    • Checks if the object passed is null or not of the same class.
    • Casts the object to Person and compares the name and age properties.
  5. hashCode Method:
    • Generates a hash code using the name's hash code and the age.
    • The 31 multiplier is used to ensure a good distribution of hash codes.
  6. toString Method: Provides a string representation of the Person object.
  7. Main Method:
    • Creates a few Person objects and tests the equals and hashCode methods.
    • Adds Person objects to a HashSet and prints the set to demonstrate that duplicates are not added.

This example demonstrates how equals and hashCode methods should be implemented to ensure that objects behave correctly in collections that rely on these methods, such as HashSet.


Subscribe to get more Posts :